在Unity3D中需要显式转换的可枚举协方差

本文关键字:枚举 方差 显式转换 Unity3D | 更新日期: 2023-09-27 18:12:19

Unity版本的c#实现了协方差,但是根据我在网上找到的任何例子,这段代码不能编译

string[] stringArray = new string[0];
IEnumerable<string> stringIEnumerable = new string[0];
// string[] implements IEnumerable<string>,
// and implicitly casts to IEnumerable<object> through covariance
IEnumerable<object> objects1 = stringArray;
// But puzzling enough, one cannot implicitly
// convert IEnumerable<string> to IEnumerable<object> here
IEnumerable<object> objects2 = stringIEnumerable;

完全错误:

error CS0266: Cannot implicitly convert type `System.Collections.Generic.IEnumerable<string>' to `System.Collections.Generic.IEnumerable<object>'. An explicit conversion exists (are you missing a cast?)

是的,我现在显式地强制转换它,但我需要知道为什么会发生这种情况。我知道Unity的c#版本不是最后一个,但这种行为让我感到非常奇怪。我认为没有中间版本的c#可以在没有这些隐式强制转换的情况下实现协方差

附录:我喜欢干净的代码。我想知道如何使这些隐式强制转换工作,因为它们在我使用它们的上下文中感觉非常正确和自然

在Unity3D中需要显式转换的可枚举协方差

协变是当前版本的Unity编译器支持的编译器特性,但实际的框架是较旧的版本,其中泛型接口没有定义为具有协变类型