zoukankan      html  css  js  c++  java
  • (C#) Action, Func, Predicate 等泛型委托

    首先需要理解 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

  • 相关阅读:
    身份证号码的秘密
    SQL Server中的DATEPART函数的使用
    VS2010+Visual Assist X
    Log4Net使用指南
    JScript中的prototype(原型)属性研究
    使用Transaction访问数据库(C#,TransactionScope,.NET 2.0)
    C# 中奇妙的函数–7. String Split 和 Join
    LinqToSQL实例参见
    得到当前网址的域名 ASP.NET
    oracle中delete、truncate、drop的区别
  • 原文地址:https://www.cnblogs.com/fdyang/p/3650595.html
Copyright © 2011-2022 走看看