c# - 与 Func<TResult> 相同的操作?

标签 c# .net 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();

我对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/

相关文章:

c# - 为什么我得到 Ice::MemoryLimitException,即使是 Ice.MessageSizeMax=2000000

C# 将 Lambda 表达式函数转换为描述性字符串

silverlight - 是否可以绑定(bind)到 Silverlight 中的 lambda 表达式?

c# - WCF服务Process.Start在网络服务帐户下模拟为其他用户

c# - 如何将 "/x"选项参数合并到 .NET 控制台应用程序中?

c# - 反转折线图的方向

c# - 在 .NET 4.0 应用程序域上加载针对 .NET 4.5 的程序集

python - 在小于 O(n) 的时间内找到小于给定数字的斐波那契和

c# - 使用 .NET C# 连接到 Interbase 7.1 的最佳方式

c# - 更新演示者对多线程事件、MVP、Winforms 的看法