C#代理那点事儿

Func代理是啥?

Func代理接收0个或多个参数,返回TResult值

以Func<TSource, TResult>为例:Func带来封装一个方法,该方法接收一个参数,然会一个TResult类型。

举个最简单的例子,求一个一维整数数组的和

private static void Demo()
{
    Func<int[], int> MySum = arr => 
    { 
        int total = 0;
        foreach (int i in arr)
            total += i;

        return total;
    };

    int[] data = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int result = MySum(data);

    Console.WriteLine(result);
}
Sum

OK,我们继续,如果我们希望复杂一点:先对数组过滤,然后求和,那么我们的代码应该如下:

private static void Demo3()
{

    int[] data = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int result = data.FilterAndSum(a => a > 7);

    Console.WriteLine(result);
}

public static class MyExtension
{
    public static int FilterAndSum(this int[] source, Func<int, bool> selector)
{ 
   int total = 0;
   foreach (int s in source)
       if (selector(s))
           total += s;

   return total;
}   
}
FilterAndSum

如果,我们希望我们的扩展方法,可以支持更改多的类型,那么我们可以这样的实现扩展方法

public static int SelectAndSum<TSource>(this IList<TSource> source, Func<TSource, int> selector)
{
    int total = 0;

    foreach (TSource s in source)
        total += selector(s);

    return total;
}

......


private static void Demo()
{
    IList<Staff> list = new List<Staff> { 
        new Staff{FirstName="AAA", LastName="111", Salary=1000},
        new Staff{FirstName="BBB", LastName="222", Salary=2000}
    };
    int result = list.SelectAndSum(s => s.Salary);

    Console.WriteLine(result);
}
Generic Extend method

另外,如果我们想自己扩展IEnumerable,那么现在我们就知道应该这样:

public static IEnumerable<TSource> CustomMethod<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> selector)
{
    foreach(TSource s in source)
        if(selector(s))
            yield return s;
}
...

private static void Demo4()
{
    IList<Staff> list = new List<Staff> { 
        new Staff{FirstName="Tom", LastName="Ng", Salary=1000},
        new Staff{FirstName="Simon", LastName="Wong", Salary=2000}
    };

    IEnumerable<Staff> list2 = list.CustomMethod(s => s.Salary > 1000);


    Console.WriteLine(list2.Count());
}
Extend IEnumerable

那么Action代理呢

Action代理不返回值,它可以接受一个或多个参数。

那么Delegete类呢?

代理就是一个指向某个类的静态方法,或者指向实例类的实例方法。

那么代理呢?

代理是定义了方法签名的类型。当你实例化一个代理类型时,你可以把该代理实例指向与代理签名相兼容的方法。然后通过代理实例调用所指向的方法

原文地址:https://www.cnblogs.com/yang_sy/p/C_Sharp_kinds_of_Delegate.html