C#=> Lambda运算符
示例
=>运算符与赋值运算符具有相同的优先级,并且具有右结合。
它用于声明lambda表达式,也广泛用于LINQ查询:
string[] words = { "cherry", "apple", "blueberry" };
int shortestWordLength = words.Min((string w) => w.Length); //5在LINQ扩展或查询中使用对象时,通常可以跳过对象的类型,因为它是由编译器推断的:
int shortestWordLength = words.Min(w => w.Length); //也会以相同的结果编译
lambda运算符的一般形式如下:
(input parameters) => expression
lambda表达式的参数在=>运算符之前指定,要执行的实际表达式/语句/块在运算符的右侧:
// 表达
(int x, string s) =>s.Length> x
// 表达
(int x, int y) => x + y
// 声明
(string x) => Console.WriteLine(x)// 块
(string x) => {
x += " 说你好!";
Console.WriteLine(x);
}此运算符可用于轻松定义委托,而无需编写显式方法:
delegate void TestDelegate(string s);
TestDelegate myDelegate = s => Console.WriteLine(s + " World");
myDelegate("Hello");代替
void MyMethod(string s){
Console.WriteLine(s + " World");
}
delegate void TestDelegate(string s);
TestDelegate myDelegate = MyMethod;
myDelegate("Hello");