【C#学习】lambda表达式

来源:互联网 发布:云端收银软件 编辑:程序博客网 时间:2024/05/20 07:59

C# 中 Lambda表达式作为一种内联函数使用,可以将一个Lambda表达式赋给一个委托(C# 3.0+)。"Lambda表达式"是一个特殊的匿名函数,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量。它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型,支持带有可绑定到委托或表达式树的输入参数的内联表达式。所有Lambda表达式都使用Lambda运算符=>,该运算符读作"goes to"。Lambda运算符的左边是输入参数(如果有),右边是表达式或语句块。Lambda表达式x => x * x读作"x goes to x times x"。以下是四个例子:

        delegate int plus(int x, int y);        delegate double sqrt(int x, int y);        delegate void print(string str);        delegate void hello();         static void Main(string[] args)        {            plus p = (x, y) => x + y; // 把lambda表达式赋给委托            sqrt c = (x, y) =>                 {                return Math.Sqrt(x * x + y * y); // lambda表达式的返回值类型必须和委托一致            };                        print pt = (str) =>                 Console.Write(str);            hello h = () => Console.WriteLine("hello, world");            int n = p(-1, 4); // 3            Console.WriteLine(n);             double n2 = c(3, 4);  // 5            Console.WriteLine(n2);            pt("print()\n"); // print()            h();         }






原创粉丝点击