委托

来源:互联网 发布:推荐一个好的昵称知乎 编辑:程序博客网 时间:2024/05/16 12:21

委托的意义:将一个方法作为参数传给另一个方法
委托的概念;声明一个委托,委托所指向的函数必须跟委托具有相同的签名(签名为返回值及形参).
匿名函数:没有名字的函数.方法体直接写在表达式中(可见于lamda表达式),多用于方法使用次数不多的方法.
普通委托语法:

  1. 申明一个委托对象
  2. 创建一个与委托对应的方法
  3. 在需要使用委托的方法形参中加上委托,并在方法体内添加委托
  4. 调用方法,将值与委托相对应的方法传入
    //该步奏可以使用匿名函数取消2方法
    //也可以直接使用lamda表达式写入

代码:

   class Program    {        static void Main(string[] args)        {            int[] str={1,2,3,45,23,423,4};            //dec<> d = test;            int o = testStr<int>(str, (int t1, int t2) => { return t1 - t2; });          Console.WriteLine(o);          Console.ReadKey();        }        public static int test<T>(int  t1, int  t2)        {            return t1 - t2;        }        public static T testStr<T>(T[] str,dec<T> d)        {            T  max=str[0];            for (int i = 0; i < str.Length; i++)            {                if (d(max,str[i]) < 0)                {                    max=str[i];                 }                            }            return max;        }    }

lamda表达式写法:

  1. 申明一个委托对象.例:public delegate void dec(string name);
  2. 创建委托对象,且直接写方法体及返回类型

=>意义为goes to
dec dsx=(string name)=>{方法体;};
dsx(“adsf”) ;

0 0
原创粉丝点击