我可以遵循任何简单的synax或规则来构建C#中的"lambda表达式"吗?我阅读了一些文章并理解了lambda表达式是什么,但是如果我有一般语法或规则会有所帮助.
Mar*_*ell 10
根据具体情况,有多种表达lambda的方法 - 一些例子:
// simplest form; no types, no brackets
Func<int, int> f1 = x => 2 * x;
// optional exlicit argument brackets
Func<int, int> f2 = (x) => 2 * x;
// optional type specification when used with brackets
Func<int, int> f3 = (int x) => 2 * x;
// multiple arguments require brackets (types optional)
Func<int, int, int> f4 = (x, y) => x * y;
// multiple argument with explicit types
Func<int, int, int> f5 = (int x, int y) => x * y;
Run Code Online (Sandbox Code Playgroud)
lambda的签名必须与所使用的委托的签名相匹配(无论是明确的,如上所述,还是由上下文所暗示的 .Select(cust => cust.Name)
您可以使用空表达式列表来使用不带参数的lambdas :
// no arguments
Func<int> f0 = () => 12;
Run Code Online (Sandbox Code Playgroud)
理想情况下,右侧的表达正是如此; 一个表达式.编译器可以将此转换为任何一个delegate 或一Expression树:
// expression tree
Expression<Func<int, int, int>> f6 = (x, y) => x * y;
Run Code Online (Sandbox Code Playgroud)
然而; 你也可以使用语句块,但这只能用作delegate:
// braces for a statement body
Func<int, int, int> f7 = (x, y) => {
int z = x * y;
Console.WriteLine(z);
return z;
};
Run Code Online (Sandbox Code Playgroud)
请注意,即使.NET 4.0 Expression树支持语句体,C#4.0编译器也不会为您执行此操作,因此Expression除非您"艰难地"执行此操作,否则您仍然只能使用简单的树.有关更多信息,请参阅我在InfoQ上的文章.
从根本上说,lambda表达式是函数指针的简写符号.更常见的是,lambda表达式是将输入数据传播到计算结果的表达式中.在大多数情况下,您将以更常见的形式使用lambda表达式:
int[] numbers = new[] { 1, 3, 11, 21, 9, 23, 7, 4, 18, 7, 7, 3, 21 };
var twentyoneCount = numbers.Where(n => n == 21).Count();
var sumOfgreaterThanSeven = numbers.Sum(n => n > 7 ? n : 0);
Run Code Online (Sandbox Code Playgroud)
在不太常见的形式中,lambda表达式可以替换更繁琐的委托形式:
myButton.Click += new EventHandler(myButton_Click);
// ...
void myButton_Click(object sender, EventArgs e)
{
// TODO: Implement button click handler here
}
Run Code Online (Sandbox Code Playgroud)
或者不那么常见,而且不那么冗长:
myButton.Click += delegate(object sender, EventArgs e)
{
// TODO: Implement button click handler here
};
Run Code Online (Sandbox Code Playgroud)
以下lambda表达式实现与上述两者相同的结果:
myButton.Click += (s,e) =>
{
// TODO: Implement button click handler here
};
Run Code Online (Sandbox Code Playgroud)
后一种形式的力量真正来自于它创造封闭的能力.闭包是在函数中实现函数,并从父函数作用域"关闭"参数和变量:
private void DoSomething(IList<string> input, SomeObject source)
{
source.OnSomeEvent += (s,e) => return input.Sum();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2342 次 |
| 最近记录: |