sin*_*ash 7 .net c# lambda delegates
我遇到了一些需要一些知识的情况.
以下是代码:
// A function to match the delegate
public static int DoSomething()
{
Console.WriteLine("i am called");
return 1;
}
// Usage
Action action = () => DoSomething();
Func<int> func = () => DoSomething();
action();
func();
Run Code Online (Sandbox Code Playgroud)
我的理解Action曾经是它应该匹配一个不接受任何参数并且不返回任何参数的委托.
为此Func<int>它应该匹配一个不接受参数并返回一个的委托int.
DoSomething方法返回一个整数,因此我的问题() => DoSomething()是:返回一个委托int.Func按预期工作,但Action没有.为什么?我在这里没有理解什么?
代码编译并正确运行,两者都是输出i am called.我想知道的是,为什么Action action = () => DoSomething();不是编译时错误?
Jon*_*eet 10
我想知道的是,为什么
Action action = () => DoSomething();不是编译时错误?
它编译是因为你有一个lambda表达式调用方法但忽略了结果.您无法使用方法组转换,例如
// Compile-time failure
// error CS0407: 'int Test.DoSomething()' has the wrong return type
Action action = DoSomething;
Run Code Online (Sandbox Code Playgroud)
(同样的方法组转换Func<Action, int>很好.)
但相反,你正在做更像这样的事情:
Action action = DoSomethingAndIgnoreResult;
...
private static void DoSomethingAndIgnoreResult()
{
DoSomething(); // Hey, I'm ignoring the result. That's fine...
}
Run Code Online (Sandbox Code Playgroud)
Action action = () => DoSomething();相当于Action action = () => { DoSomething(); };
Func<int> func = () => DoSomething();相当于Func<int> func = () => { return DoSomething(); };