C#铸造一个List< ObjBase>如表<&的OBJ GT;
问题描述:
为什么我不能投了列表< ObjBase>
为列表<的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>();
}
}
相反,我必须这样做:
Instead I have to do this:
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
感谢。