您的位置:首页 > 编程学习 > ASP.NET > 正文

asp.net func 委托

更多 时间:2015-12-7 类别:编程学习 浏览量:1337

asp.net func 委托

asp.net func 委托

Func委托是system下的全局函数,不用我们自定,系统自定义的,供我们使用,带有多个重载.

一、Func<T>委托的定义

  •  
  • 
            public delegate TResult Func<TResult>();
            public delegate TResult Func<T1, TResult>(T1 arg1);
            public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
            public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
            public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
            public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
    
    		
  •  

    二、参数说明

    1、TResult表示。
    2、委托所返回值 所代表的类型, T,T1,T2,T3,T4表示委托所调用的方法的参数类型。

    3、Func委托声明的最后一个泛型类型参数是委托所接收方法的返回值类型,前面的泛型类型参数(如果有的话)就是委托所接收的方法的形参类型。

     

    三、Func委托实例

     

  •  
  • C# 代码   复制
  • 
    static long Add(int x ,int y)
    
    {
    
        return x + y;
    
    }
    
    static void Main(string[] args)
    
    {
    
        //以下泛型委托变量接收拥有两个int类型参数,返回一个long数值的方法。
    
        Func<int,int,long> func = Add;
    
        long result = func(100,200); //result=300
    
    }
    
    		
  •  

  •  
  • C# 代码   复制
  • 
    Func<int, bool> myFunc = null;//全部变量
    
    myFunc = x => CheckIsInt32(x); 
    //给委托封装方法的地方 使用了Lambda表达式
    
    private bool CheckIsInt32(int pars)//被封装的方法
    {
      return pars == 5;
    }
    
    bool ok = myFunc(5);//调用委托
    
    		
  •  

  •  
  • C# 代码   复制
  • 
    namespace FuncAsFuncArgu
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
                Console.WriteLine(Process(Add, numbers, 0, 5));
                Console.WriteLine(Process(Multiply, numbers, 1, 5));
                Console.ReadKey();
            }
    
            static int Process(Func<int, int, int> op, int[] numbers, int from, int to)
            {
                int result = numbers[from];
                for (int i = from + 1; i <= to; i++)
                    result = op(result, numbers[i]);
                return result;
            }
    
            static int Add(int i, int j)
            {
                return i + j;
            }
    
            static int Multiply(int i, int j)
            {
                return i * j;
            }
        }
    }
    
    		
  •  

     

    标签:委托