且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么lambda可以将函数调用转换为Action?

更新时间:2022-05-13 01:28:37

lambda表达式的类型 x =>Print(x)是根据其上下文确定的.由于编译器知道将lambda分配给 Action< string> ,因此编译器会忽略 Print 方法的返回类型,就好像它是语句表达式.

The type of the lambda expression x => Print(x) is determined based on its context. Since the compiler knows that the lambda is assigned to Action<string>, the compiler disregards the return type of the Print(s) method as if it were a statement expression.

这是有效的转换:

Action<string> myAction = y => Print(y);

换句话说,两者

Print("something");

int x = Print("something");

Print 方法的正确用法;它们可以以相同的方式在lambda中使用.

are correct usages of the Print method; they can be used in lambdas in the same way.