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

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

问题描述:

在此代码片段中:

List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Tom");
names.Add("Tim");
names.Add("Richard");

names.ForEach(x => Print(x));

private static string Print(string s)
{
    Console.WriteLine(s);
    return s;
}

Print 肯定不是 Action ,因为它返回的是 string ;但是 x =>Print(x)是,为什么?

Print is not an Action for sure since it is returning string; however x=> Print(x) is, why?

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.