gpt4 book ai didi

c# - 为什么 Func<...> 和 Action 不统一?

转载 作者:可可西里 更新时间:2023-11-01 07:58:11 27 4
gpt4 key购买 nike

我发现自己一直想传递一个有返回值且没有输入的 Func 来代替 Action,例如

Func<int> DoSomething = ...;

Task.Run(DoSomething);

在哪里,我真的不关心 DoSomething 的返回值。

但是,这些类型并不统一,我最终结束了调用

Task.Run(() => { DoSomething(); });

有没有办法在不包装的情况下使这些类型统一?另外,它们不统一是否有好的设计原因?

最佳答案

您希望以下陈述为真:

If I have a Func<T>, I should be able to use it where an Action is required.

这需要 Func<T> (A) 可分配给 Action(B) 隐式转换为 Action .

如果我们假设 (A) 那将需要 T ,可以是任何类型,可分配给 void .

Eric Lippert 在 his blog 中回答了这个问题:

Shouldn’t “void” be considered a supertype of all possible types for the purposes of covariant return type conversions from method groups to delegate types?

他的回答是“否”,因为这最终与 CLI 规范不兼容。 CLI 规范要求返回值进入堆栈,因此 void函数最终不会生成“pop”指令,而那些返回某些东西的函数会生成“pop”指令。如果有某种方式可以包含一个“ Action ”void函数或返回在编译时未知的东西的函数,编译器不知道是否生成“pop”指令。

他接着说:

Had the CLI specification said “the returned value of any function is passed back in a ‘virtual register’” rather than having it pushed onto the stack, then we could have made void-returning delegates compatible with functions that returned anything. You can always just ignore the value in the register. But that’s not what the CLI specified, so that’s not what we can do.

换句话说,如果有这个存储函数返回值的“虚拟寄存器”(在 CLI 规范中可能不存在),C# 及其编译器的编写者可以完成您想要的,但是他们不能,因为他们不能偏离 CLI 规范。

如果我们假设(B),就会出现重大变化,正如 Eric Lippert 在 this blog 中解释的那样.如果有从 Func<T> 的隐式转换,则将他博客中的示例改编为此示例至 Action ,一些程序不再编译(中断更改)。该程序目前可以编译,但尝试取消对隐式转换运算符的注释,类似于您所要求的,它不会编译。

public class FutureAction
{
public FutureAction(FutureAction action)
{
}

//public static implicit operator FutureAction(Func<int> f)
//{
// return new FutureAction(null);
//}

public static void OverloadedMethod(Func<FutureAction, FutureAction> a)
{
}

public static void OverloadedMethod(Func<Func<int>, FutureAction> a)
{
}

public static void UserCode()
{
OverloadedMethod(a => new FutureAction(a));
}
}

(这显然不是他们要做的,因为这只适用于 Func<int> 而不是 Func<T> ,但它说明了问题。)

总结

我认为您面临的问题是 CLI 规范的产物,当时可能没有预见到,我猜他们不想引入重大更改以允许隐式转换为工作。

关于c# - 为什么 Func<...> 和 Action 不统一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33150506/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com