Lambda的前世今生

先看一段代码吧

class Student{
    delegate void Say(string content);
    public void Show()
    {
        //Lambda的前世今生
        //总结:Lambda就是委托的参数
        {
            //匿名委托
            Say say = new Say(delegate(string content)
            {
                Console.WriteLine("xiao ming say hello:"+content);
            });
            say.Invoke("xiaoming");
        }
        {
            //取消new Say,不用单独写实例化代码
            Say say = delegate(string content)
            {
                Console.WriteLine("xiao ming say hello:" + content);
            };
            say.Invoke("xiaoming");
        }
        {
            //取消delegate关键字,并增加 =>
            Say say = (string content)=>
            {
                Console.WriteLine("xiao ming say hello:" + content);
            };
            say.Invoke("xiaoming");
        }
        {
            //取消参数的类型,编译器自动推断,同时一个参数可以取消括号
            Say say = content =>
            {
                Console.WriteLine("xiao ming say hello:" + content);
            };
            say.Invoke("xiaoming");
        }
        {
            //如果只有一行代码,还可以取消大括号,写成一行
            Say say = content =>Console.WriteLine("xiao ming say hello:" + content);
            say.Invoke("xiaoming");
        }
    }
}

 通过上面我们可以看到委托的演变过程,到最后就是我们熟悉的Lambda表达式,Lambda表达式是.net framwork 3.0推出的。

1.委托是一种类型。

2.Lambda表达式是委托的参数。

原文地址:https://www.cnblogs.com/duanjt/p/10476225.html