C# 中的Action Func

来源:互联网 发布:mui.js 编辑:程序博客网 时间:2024/03/29 08:19

昨天在群里请教了一个问题,学到了不少:


看这个函数的声明

 public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);



感觉有点神奇. 决定研究一下.


看了一下c#高级编程第七版, 重新学习了一下 Action 和 Func

如何定义一个和数组中  Select  类似的函数:


   static int get_sum(int x, int y)
    {
      return x + y;
    }
    static T test_sum<T>(T x, T y, Func<T, T, T> sum)
    {
      return sum(x, y);
    }


调用方:

  int x = test_sum(1, 4, get_sum);



再扩展一下知识,定义一个返回值不同的:

   static W test_sum1<T,W>(T x, T y, Func<T, T, W> sum)
    {
      return sum(x, y);
    }


当然你也可以定义N个这参数类型不同的模版参数.


注: 它和c++不同的是不用显式的模版类型., 返回值类型也是在 函数名后. 




Action  多播委托:


    static void showfun1()
    {
      Console.WriteLine("show1");
    }
    static void showfunint(int x)
    {
      Console.WriteLine(x);
    }


     

     Action d1 = showfun1;
      d1 += showfun1;
      d1();
      Action<int> d2 = showfunint;
      d2 += showfunint;

     


这个其实比较简单.

注意Action 不能有返回值, 如果在调用过程中出错,下面的委托不再会调用到.






原创粉丝点击