C# 模板内浇铸的内在价值问题

C# 模板内浇铸的内在价值问题,c#,.net,list,generics,casting,C#,.net,List,Generics,Casting,我无法共享我的代码,但基本上我有一个实现接口的类,如下所示: public interface A { void doA(); } public class B: A { public void doA() { // Doing A } } 我有一份类似的清单: List<B> list = new List<B>(); list.Add(new B()); List List=新列表(); 添加(新的B()); 现在我想

我无法共享我的代码,但基本上我有一个实现接口的类,如下所示:

public interface A
{
    void doA();
}

public class B: A
{
    public void doA()
    {
     // Doing A
    }
}
我有一份类似的清单:

List<B> list = new List<B>();
list.Add(new B());
List List=新列表();
添加(新的B());
现在我想要一个
IEnumerable
。所以我试了以下三行:

List<A> listCast = (List<A>)list;
IEnumerable<A> listCastToEnumerable = (IEnumerable<A>)list;
IEnumerable<A> listCastExt = list.Cast<A>();
List listCast=(List)List;
IEnumerable列表CastToEnumerable=(IEnumerable)列表;
IEnumerable ListCastText=list.Cast();
  • 第一个出现错误:
  • “错误1无法转换类型
    'System.Collections.Generic.List'
    'System.Collections.Generic.List'

  • 第二个没有得到错误,但得到了
    InvalidCastException

  • 第三个成功了

  • 我的问题是:

  • 为什么第一行出错而第二行没有
  • 为什么前两行是无效的
  • 做这种演员最好的方法是什么?第三行是好的还是有更好的方法
  • 让我们把它分解一下

    1.
    为什么第一行出现错误而第二行没有

    在第二行,您将转换为协变的
    IEnumerable(T)

    2.
    为什么前两行无效

    即使在您强制转换
    列表时
    仍会保留其基本类型信息,这意味着它不能保存类型A的项目,而类型B也不是

    3.
    做这种演员的最佳方式是什么?第三行是好的还是有更好的方法

    第三行将
    列表
    中的每个元素转换为类型A,并返回类型A的新
    IEnumerable(T)
    。这可以迭代为类型A的新
    列表
    ,该列表将愉快地保存类型A的任何元素。

    您也可以这样做

     IEnumerable<A> listoftypeb = list.OfType<A>();
    
    IEnumerable listoftypeb=list.OfType();
    

    这将为您提供一个没有错误的a列表,如果您有一个不能按大小写键入a的元素

    您需要创建一个IEnumerable(t)并用列表中的数据填充它,因为
    List
    不是
    IEnumerable

    所有的狗都是动物,但不是所有的动物都是狗。。。或者说,您在哪个版本的.NET上运行它?