简体   繁体   English

为什么 C# Func<int> 不能分配给 Func<object> ?<div id="text_translate"><p> 我在 C# 研究了协变和逆变。下面我的代码有一个错误。</p><pre> object a = new object(); int b = 10; a = b; // not error Func<object> acO = () => new object(); Func<int> acI = () => 1; acO = acI; // error</pre><p> 错误信息:</p><blockquote><p> 无法将类型“System.Func”隐式转换为类型“System.Func”。</p></blockquote><p> 我认为如果 int -> object 是可能的,那么 Func -> Func 将是可能的。 但事实并非如此。</p><p> 我认为值类型在返回时将被复制以使用,这与引用类型(对象)不同,并且它可能导致意外操作(如异常)。 我的猜测正确吗?</p><p> 我期待着您明智的回答。 感谢您阅读。</p></div></object></int>

[英]Why C# Func<int> cannot be assigned to Func<object>?

I've studied Covariant and Contravariant in C#. and below my code has an error.我在 C# 研究了协变和逆变。下面我的代码有一个错误。

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

a = b; // not error


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

acO = acI; // error

Error Message:错误信息:

Cannot implicitly convert type 'System.Func' to type 'System.Func'.无法将类型“System.Func”隐式转换为类型“System.Func”。

I thought that if int -> object is possible, Func -> Func will be possible.我认为如果 int -> object 是可能的,那么 Func -> Func 将是可能的。 but it is not.但事实并非如此。

I think value type will be copied to use when it is returned unlike reference type(object) and it can cause unintentional operation(like exception).我认为值类型在返回时将被复制以使用,这与引用类型(对象)不同,并且它可能导致意外操作(如异常)。 Is my guess correct?我的猜测正确吗?

I'm looking forward to your wise answers.我期待着您明智的回答。 Thank you for reading.感谢您阅读。

From the Variance in Delegates (C#) docs:来自委托方差 (C#)文档:

Variance for generic type parameters is supported for reference types only.仅引用类型支持泛型类型参数的变体。

A niceblog post diving into the topic by Eric Lippert: 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.这就是为什么接口和委托类型的协变和逆变转换要求所有可变类型 arguments 都是引用类型。 To ensure that a variant reference conversion is always identity-preserving, all of the conversions involving type arguments must also be identity-preserving.为确保变体引用转换始终保持身份,涉及类型 arguments 的所有转换也必须保持身份。 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.确保类型 arguments 上的所有非平凡转换都保持身份的最简单方法是将它们限制为引用转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM