C#基本功------委托和事件(二)--拉姆达表达式

委托的另一种用法---------匿名方法:

public delegate void MyDel(string msg);----声明的委托
    class Program
    {
        static void Main(string[] args)
        {
            MyDel mdl = delegate(string str) { Console.WriteLine(str); };
            mdl("床前明月光");
            Console.ReadKey();
        }
    }
另一种简单的写法
  public delegate void MyDel(string msg);
    class Program
    {
        static void Main(string[] args)
        {
            MyDel mdl = (string str)=> { Console.WriteLine(str); };------------将delegate简化成=>,这种方法逐渐的演化成了拉姆达表达式
            mdl("床前明月光");
            Console.ReadKey();
        }
    }

下面我们来看下拉姆达表达式

 public delegate void MyDel(string msg);----void改成string
    class Program
    {
        static void Main(string[] args)
        {
            MyDel md = x => x + "厉害";---会在这句话报错,如果我们把上面的返回值的类型改成string,就不会报错了,这是为什?因为x=>x+"厉害"相当于是返回值,返回回去了
            Console.ReadKey();
            
        }
    }

再举个例子:

   static void Main(string[] args)
        {
            T1((x, y, z) => x + y + z);-------------拉姆达表达式的使用
            Console.ReadKey();
        }
        public static void T1(myDel menth)
        {
            int result = menth(10, 20, 10);
            Console.WriteLine(result);
        }
        public delegate int myDel(int a,int b,int c);
原文地址:https://www.cnblogs.com/guyali/p/5342734.html