c# - 仅在 3.5 中从 List<T> 到 IEnumerable<T> 的 InvalidCastException

标签 c# .net exception casting

如果我这样称呼

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> )。

MSDN

关于c# - 仅在 3.5 中从 List<T> 到 IEnumerable<T> 的 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30200003/

相关文章:

c# - 如何创建一个项目来为支持 iOS、Android 和 UWP 的 Xamarin Forms 创建 Nuget 包?

c# - EventFiringWebDriver 不通知事件

c# - 如何代码重用apsx?

java - 在Java中,我有一个名为字符串 "A"(大小1)的字符串。为什么 string.substring(1) 没有给出异常

python - 一个 block 中的多个尝试代码

c++ - 异常继承

c# - 如何在 C# 程序中生成一组随机字符串,以便不轻易预测它们?

c# - 具有多个存储库的 ASP.NET MVC Controller ?

asp.net - 在 Web 应用程序中对长时间运行的任务进行排队

.net - 构建通用实用程序库的最佳方法是什么?