C# 将 List<ObjBase> 转换为 List<Obj>

标签 c# generics inheritance list casting

为什么我不能投 List<ObjBase>作为List<Obj> ?为什么以下不起作用:

internal class ObjBase
   {
   }

internal class Obj : ObjBase
   {
   }   

internal class ObjManager
{
    internal List<Obj> returnStuff()
    {
       return getSomeStuff() as List<Obj>;
    }

    private List<ObjBase> getSomeStuff()
    {
       return new List<ObjBase>();
    }

}

相反,我必须这样做:

internal class ObjBase
   {
   }

internal class Obj : ObjBase
   {
   }

internal class ObjManager
{
    internal List<Obj> returnStuff()
    {
       List<ObjBase> returnedList = getSomeStuff();
       List<Obj> listToReturn = new List<Obj>(returnedList.Count);
       foreach (ObjBase currentBaseObject in returnedList)
       {
          listToReturn.Add(currentBaseObject as Obj);
       }
       return listToReturn;
    }

    private List<ObjBase> getSomeStuff()
    {
       return new List<ObjBase>();
    }
}

我在 Visual Studio 2008 中收到以下错误(为了便于阅读而缩短):

Cannot convert type 'List' to 'List' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

谢谢。

最佳答案

您可以使用 System.Linq 中的 CastToList 扩展方法将其放在一行中。

代替

internal List<Obj> returnStuff()
{
   return getSomeStuff() as List<Obj>;
}

这样做:

internal List<Obj> returnStuff()
{
   return getSomeStuff().Cast<Obj>().ToList();
}

关于C# 将 List<ObjBase> 转换为 List<Obj>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1266014/

相关文章:

c# - 如何从另一个文件中找到对 Git 中函数的调用?

c# - 在 ASP.NET 中使用 Ext JS

c# - C++ 和 C# 规范?

Java Generics - 难以执行强类型检查

objective-c - Objective-C 中的结构继承?

javascript继承框架

c# - 如何在 C# 中将此 SQL 转换为 LINQ?

java - Wicket 中的 Form<Void> (或一般使用 Void 类型)

generics - 具有唯一 ID 的 Haskell 泛型

python - Python3 中的子类化类型与对象