问题描述
我有以下的类层次结构:
I have the following class hierarchy:
public abstract class BaseData
{
//some properties
}
public class CoData : BaseData
{
//some properties
}
我与要求返回类型是一个方法的工作名单,其中,BaseData>
。在该方法中,我有机会获得名单,其中,CODATA>
I am working with a method that requires the return type to be List<BaseData>
. In the method, I have access to List<CoData>
public List<BaseData> Save()
{
List<CoData> listCoData = GetData();
return listCoData;
}
如果我理解正确的话,我可以上溯造型从 CODATA
到 BaseData code>。但是,当我有一个列表,它的错误了,即使我明确地尝试强制转换。
If I understand correctly, I can upcast from a CoData
to a BaseData
. But, when I have a list, it errors out even if I explicitly try to typecast.
错误:
Error 118 Cannot implicitly convert type 'System.Collections.Generic.List<CoData>' to System.Collections.Generic.List<BaseData>'
编辑:
mquander的转换方法似乎在3.0为我工作。
mquander's Conversion approach seems to work for me in 3.0
时的向下转换做了同样的方式呢?从
Is downcasting done the same way as well? from
也就是说,我可以做到这一点 - 名单,LT;。CODATA&GT; listCoData = listBaseData.Cast&LT; BaseData&GT;()了ToList();
ie., Can I do this - List<CoData> listCoData = listBaseData.Cast<BaseData>().ToList();
推荐答案
是的;欢迎方差。最终,它的不是列表 BaseData code> - 例如,如果你有另一个小类中,一个
名单,其中,BaseData&GT ;
将(在编译时),让你。新增
...但在运行时类型不会放过你的。编译器阻止你犯了一个错误。
Yes; welcome to variance. Ultimately, it isn't a list of BaseData
- for example, if you had another subclass, a List<BaseData>
would (at compile time) let you .Add
it... but the runtime type wouldn't let you. The compiler is stopping you making a mistake.
在某些情况下,仿制药可以帮助这里...我讨论这个在的。需要注意的是.NET 4.0方差不适用于列表
In some scenarios, generics can help here... I discuss this at the end of this blog entry. Note that .NET 4.0 variance doesn't apply to lists.
这篇关于上溯造型和泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!