如果我这样称呼
var list = new List<Class1>();
Test((IEnumerable<Interface1>)list);
与
public interface Interface1
{
}
public static void Test(IEnumerable<Interface1> test)
{
}
public class Class1 : Interface1
{
}
我在 3.5 框架中得到一个 InvalidCastException,但在 4 和 4.5 中没问题。而且我不明白为什么,两者都有 IEnumerable
如果我检查 3.5 和 4.5 中的列表,我不明白为什么会得到 InvalidCastException
4.5:
public class List<T> : IList<T>, ICollection<T>,
IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>
3.5:
public class List<T> : IList<T>, ICollection<T>,
IEnumerable<T>, IList, ICollection, IEnumerable
最佳答案
在 3.5 中,IEnumerable<T>
接口(interface)不是协变的。这是在 4.0 中添加的。
需要协方差才能转换为更派生的类型,这里就是这种情况( List<T>
实现 IEnumerable<T>
)。
关于c# - 仅在 3.5 中从 List<T> 到 IEnumerable<T> 的 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30200003/