【发布时间】:2023-03-10 09:30:01
【问题描述】:
我遇到了需要一些知识的情况。
下面是代码:
// 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的理解是应该匹配一个不接受参数也不返回任何内容的委托。
对于Func<int>,它应该匹配一个不接受参数并返回int的委托。
DoSomething 方法返回一个整数,因此我的问题是:() => DoSomething() 是一个返回 int 的委托。 Func 按预期工作,但 Action 没有。为什么?我在这里有什么不明白的地方?
代码编译运行正常,均输出i am called。我想知道的是为什么Action action = () => DoSomething();不是编译时错误?
【问题讨论】:
-
>> 但 Action 没有 — 它究竟是如何失败的?
-
代码行
Action<object> action = (x) => DoSomething(x);,不应该是编译时错误,因为Action<object>需要匹配不返回值的委托吗? -
@singsuyash C# 编译器足够聪明,可以根据上下文确定
(x) => DoSomething(x)的含义不同。当您使用它来分配Action变量时,它会生成Action,而不是Func,并忽略DoSomething(x)的返回结果。 -
您可以调用
DoSomething方法并“忽略”返回值(例如DoSomething(x)),您可以使用返回值(例如var retVal = DoSomething(x))- 两者都可以工作和编译。 -
您的问题是什么?您的代码非常好,可以编译并运行