具有void输入的Lambda表达式

Luk*_*Luk 30 c# lambda c#-3.0

好的,非常愚蠢的问题.

x => x * 2
Run Code Online (Sandbox Code Playgroud)

是一个lambda,代表与委托相同的东西

int Foo(x) { return x * 2; }
Run Code Online (Sandbox Code Playgroud)

但是什么是lambda相当于

int Bar() { return 2; }
Run Code Online (Sandbox Code Playgroud)

??

非常感谢!

out*_*tis 38

相当于nullary lambda () => 2.


Ahm*_*eed 19

那将是:

() => 2
Run Code Online (Sandbox Code Playgroud)

用法示例:

var list = new List<int>(Enumerable.Range(0, 10));
Func<int> x = () => 2;
list.ForEach(i => Console.WriteLine(x() * i));
Run Code Online (Sandbox Code Playgroud)

根据评论中的要求,以下是上述样本的细分......

// 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
Run Code Online (Sandbox Code Playgroud)


Ste*_*ins 9

如果没有参数,可以使用().

() => 2;
Run Code Online (Sandbox Code Playgroud)