Have fun with sci.dog

C# 为对象扩展方法

最近碰到一个需求,就是要对数组做一个切片,python和matlab对数组切片非常简单,用start:end就可以,那么能不能让C#的数组也拥有类似的功能呢,经过查询,找到了这个很好的办法。

思路就是用C#的静态类配合this关键字

先看代码

// See https://aka.ms/new-console-template for more information

double[] A = {1,2,3,4,5,6,7,8,9,10};
double[] B = A.Slice(3,5);
foreach(double x in B)
    Console.WriteLine("{0}",x);

public static class MyExtension
{
    public static T[] Slice<T>(this T[] source, int start, int end)
    {
        if (end < 0)
        {
            end = source.Length + end;
        }
        int len = end - start;

        T[] res = new T[len];
        for (int i = 0; i < len; i++)
        {
            res[i] = source[i + start];
        }
        return res;
    }
}

这里定义了一个MyExtension静态类,实际上名称不重要。

MyExtension类里定义了一个Silice的模板方法,数组类模板,这个方法的第一个参数是this,指向了数组本身。定义了切片方法slice。看看运行结果

[Running] cd "e:\gouff\OneDrive\study\C#\2\" && dotnet run
4
5

[Done] exited with code=0 in 1.979 seconds

这个方法使用就非常简单了,直接可以作为数组对象的方法去调用,非常方便。

我们看vs的提示

vs提示,这是一个扩展方法,非常方便。

实际上,我们可以在我们的任何一个C#项目里,都建立一个MyExtension的静态类,用来给对象从外部添加扩展方法。

当然,这个类的方法不能太多,太复杂。静态类是直接加载到内存的,适合于对象的一些常用方法。

本文参考链接

https://blog.csdn.net/shuaishifu/article/details/44078145

赞(0)
未经允许不得转载:SciDog » C# 为对象扩展方法

评论 抢沙发