湖边的白杨树

探索是一种乐趣

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

首先需要理解 Delegate, Action, Func, Predicate 從根本原理上講都是函數指針,只不過傳入參數和返回值有所限定。

所有的Action, Func, Predicate 都可以轉化成 delegate 來實現。 

(1). delegate

        delegate我们常用到的一种声明

    Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型。

    例:public delegate string MethodDelegate(int x, int y);表示有两个参数,并返回string型。

  (2). Action

       Action是无返回值的泛型委托。

   Action 表示无参,无返回值的委托

   Action<int,string> 表示有传入参数int,string无返回值的委托     = delegate void MethodDelegate(int num, string str); 

   Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托

       Action<int,int,int,int> 表示有传入4个int型参数,无返回值的委托

   Action至少0个参数,至多16个参数,无返回值。

   例:

        public void Test<T>(Action<T> action,T p)
        {
            action(p);
        }

    (3). Func

   Func是有返回值的泛型委托

   Func<int> 表示无参,返回值为int的委托

   Func<object,string,int> 表示传入参数为object, string 返回值为int的委托   = delegate int MethodDelegate(object obj, string str);

   Func<object,string,int> 表示传入参数为object, string 返回值为int的委托

   Func<T1,T2,,T3,int> 表示传入参数为T1,T2,,T3(泛型)返回值为int的委托

   Func至少0个参数,至多16个参数,根据返回值泛型返回。必须有返回值,不可void

      例:   

        public int Test<T1,T2>(Func<T1,T2,int>func,T1 a,T2 b)
        {
            return func(a, b);
        }

    (4) .predicate

   predicate 是返回bool型的泛型委托

   predicate<int> 表示传入参数为int 返回bool的委托    = delegate bool MethodDelegate(int num);

   Predicate有且只有一个参数,返回值固定为bool

   例:public delegate bool Predicate<T> (T obj)

 

 參考:

https://www.cnblogs.com/akwwl/p/3232679.html

posted on 2014-04-07 20:00  fdyang  阅读(307)  评论(0编辑  收藏  举报