委托和匿名方法、lambda表达式

来源:互联网 发布:从零开始学java 第三版 编辑:程序博客网 时间:2024/04/28 01:26

CODE:

using System;namespace CsDev{    delegate void delTest(string a);//委托定义    delegate void delTest1(int a,params int[] b);     public class c2     {         void testMethod(string a)         {             Console.WriteLine("执行委托方法1 "+a);         }         public static void Main()         {             c2 c = new c2();             delTest d = c.testMethod;//方法绑定到委托方法列表             //使用匿名方法形成组合委托             d += delegate             {                 Console.WriteLine("匿名方法! ");             };             d("测试委托");             Console.WriteLine();             delTest1 d1 = delegate(int a, int[] b)             {                 Console.WriteLine("多参数委托方法:");                 Console.WriteLine(a);                 foreach (var v in b)                     Console.Write("{0} ", v);             };             d1(5,new int[]{1,2,3,4,5});             Console.ReadKey();         }     }}

输出:

执行委托方法1 测试委托
匿名方法!


多参数委托方法:
5
1 2 3 4 5


using System;namespace CsDev{    delegate int delTest(int a);//委托定义     public class c2     {         public static void Main()         {             c2 c = new c2();             delTest d;//声明委托变量             //匿名方法             d = delegate{ return 3 + 5;};                          Console.WriteLine(d(0));             //lambda表达式             delTest d1 = a =>a*a;             Console.WriteLine(d1(5));             Console.ReadKey();         }     }}

输出:

8

25


泛型委托:

using System;namespace CsStudy{    delegate R MyDel<T, R>(T value);//泛型委托    class Per    {        static public int Print(string s)        {            Console.WriteLine(s);            return 10;        }    }    class Program    {        static void Main()        {            var myDel = new MyDel<string, int>(Per.Print);            Console.WriteLine(myDel("Hello"));            Console.ReadKey();        }    }}

输出:

Hello
10


0 0
原创粉丝点击