【发布时间】:2013-05-29 00:06:59
【问题描述】:
好的,非常愚蠢的问题。
x => x * 2
是一个 lambda,表示与
的委托相同的事物int Foo(x) { return x * 2; }
但是什么是 lambda 等价物
int Bar() { return 2; }
??
非常感谢!
【问题讨论】:
好的,非常愚蠢的问题。
x => x * 2
是一个 lambda,表示与
的委托相同的事物int Foo(x) { return x * 2; }
但是什么是 lambda 等价物
int Bar() { return 2; }
??
非常感谢!
【问题讨论】:
空值 lambda 等效项是 () => 2。
【讨论】:
那就是:
() => 2
示例用法:
var list = new List<int>(Enumerable.Range(0, 10));
Func<int> x = () => 2;
list.ForEach(i => Console.WriteLine(x() * i));
根据 cmets 的要求,以下是上述示例的细分...
// initialize a list of integers. Enumerable.Range returns 0-9,
// which is passed to the overloaded List constructor that accepts
// an IEnumerable<T>
var list = new List<int>(Enumerable.Range(0, 10));
// initialize an expression lambda that returns 2
Func<int> x = () => 2;
// using the List.ForEach method, iterate over the integers to write something
// to the console.
// Execute the expression lambda by calling x() (which returns 2)
// and multiply the result by the current integer
list.ForEach(i => Console.WriteLine(x() * i));
// Result: 0,2,4,6,8,10,12,14,16,18
【讨论】:
如果你没有参数,你可以使用 ()。
() => 2;
【讨论】:
lmabda 是:
() => 2
【讨论】: