IEnumerable协方差需要在Unity3D中进行显式转换

时间:2016-10-10 17:32:13

标签: c# unity3d covariance

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#在没有这些隐式转换的情况下实现协方差

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

1 个答案:

答案 0 :(得分:1)

原来,协方差是Unity编译器当前版本支持的编译器功能,但实际框架是旧版本,其中通用接口未定义为具有协变类型

相关问题