如果我有以下类(class):
public class MyItems : List<MyItem>
{
..
}
public class MyItem : Item
{
..
}
我怎样才能将 MyItems 的实例转换回 List<Item>
?我试过进行显式转换,但出现异常。
最佳答案
你不能,因为 C# 不支持泛型变体 (see here for discussion of terminology),即使支持,它也不允许这种情况,因为如果你可以将 MyItems 转换为 List<Item>
, 你可以调用 Add(someItemThatIsntAMyItem)
,这将违反类型安全(因为 MyItems 只能包含 MyItem 对象,而不是任意项)。
参见 this question (或在 SO 中搜索“c# generic variance”)以获取有关此问题和 C# 4 future 更改的更多信息(尽管这些不会影响您的具体情况)。
关于c# casting 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036258/