【发布时间】:2012-11-24 21:39:06
【问题描述】:
我正在更多地了解这个世界。 在我的测试中,我发现这很奇怪:
[TestMethod]
public void VarianceTest()
{
List<string> listValues = new List<string>();
string[] arrayValues = listValues.ToArray();
var result = HelperCoVariant.GetTest<int>(listValues); // error to compile
var result2 = HelperCoVariant.GetTest<int>(arrayValues); // sucess
}
任何方法:
public static class HelperCoVariant
{
public static IEnumerable<T> GetTest<T>(this IEnumerable<object> t)
{
foreach (var item in t)
{
yield return (T)item;
}
}
}
我明白了。 NET 4 完美运行,因为
IEnumerable<out T>
但是为什么。 NET 3.5,有这种行为吗?
【问题讨论】:
-
因为 C# 3 不支持泛型类型的协变或逆变...
标签: c# generics collections .net-3.5 covariance