C#转换列表< ObjBase>作为List< Obj> [英] C# Casting a List<ObjBase> as List<Obj>
本文介绍了C#转换列表< ObjBase>作为List< Obj>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我不能将 List< ObjBase>
作为 List< Obj>
为什么以下无效:
Why can I not cast a List<ObjBase>
as List<Obj>
? Why does the following not work:
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中收到以下错误为可读性):
I get the following error in Visual Studio 2008 (shortened for readability):
无法通过引用转换,装箱转换,拆箱转换,或空类型转换
Cannot convert type 'List' to 'List' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
感谢。
推荐答案
请查看以下问题:
这篇关于C#转换列表< ObjBase>作为List< Obj>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文