我遇到了需要一些知识的情况。
代码如下:
// 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();
我对Action
的理解曾经是它应该匹配一个不接受任何参数且不返回任何内容的委托(delegate)。
对于 Func<int>
它应该匹配一个不接受任何参数并返回 int
的委托(delegate).
DoSomething
方法返回一个整数,因此我的问题是:() => DoSomething()
是一个返回 int
的委托(delegate). Func
按预期工作,但是 Action
没有。为什么?我在这里不明白什么?
代码编译运行正常,均输出i am called
.我想知道的是为什么 Action action = () => DoSomething();
是不是编译时错误?
最佳答案
What i want to know is that why
Action action = () => DoSomething();
is not a compile time error?
它可以编译,因为您有一个调用该方法但忽略结果的 lambda 表达式。您不能使用方法组转换,例如
// Compile-time failure
// error CS0407: 'int Test.DoSomething()' has the wrong return type
Action action = DoSomething;
(Func<Action, int>
的相同方法组转换没问题。)
但相反,您正在做更像这样的事情:
Action action = DoSomethingAndIgnoreResult;
...
private static void DoSomethingAndIgnoreResult()
{
DoSomething(); // Hey, I'm ignoring the result. That's fine...
}
关于c# - 与 Func<TResult> 相同的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33283602/