gpt4 book ai didi

c# - 为什么 C# Func 不能赋值给 Func
转载 作者:行者123 更新时间:2023-12-05 04:19:10 28 4
gpt4 key购买 nike

我学习了 C# 中的协变和逆变。在我的代码下面有一个错误。

object a = new object();
int b = 10;

a = b; // not error


Func<object> acO = () => new object();
Func<int> acI = () => 1;

acO = acI; // error

错误信息:

Cannot implicitly convert type 'System.Func' to type 'System.Func'.

我认为如果 int -> object 是可能的,那么 Func -> Func 也是可能的。但事实并非如此。

我认为值类型在返回时将被复制以使用,这与引用类型(对象)不同,它可能导致意外操作(如异常)。我的猜测是否正确?

我期待着您明智的回答。感谢您的阅读。

最佳答案

来自Variance in Delegates (C#)文档:

Variance for generic type parameters is supported for reference types only.

一个不错的blog post深入探讨 Eric Lippert 的主题:

All the built-in reference conversions are identity-preserving. This is why covariant and contravariant conversions of interface and delegate types require that all varying type arguments be of reference types. To ensure that a variant reference conversion is always identity-preserving, all of the conversions involving type arguments must also be identity-preserving. The easiest way to ensure that all the non-trivial conversions on type arguments are identity-preserving is to restrict them to be reference conversions.

关于c# - 为什么 C# Func<int> 不能赋值给 Func<object>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74930377/

28 4 0