C#:没有来自 Class<Child> 的隐式转换到 Class<Base> [英] C#: No implict conversion from Class<Child> to Class<Base>
本文介绍了C#:没有来自 Class<Child> 的隐式转换到 Class<Base>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码段无法编译.出现以下错误:
Following snippet wouldn't compile. With following error:
无法隐式转换类型 'Container
Cannot implicitly convert type 'Container<ChildClass>' to 'Container<BaseClass>'
class BaseClass {}
class ChildClass : BaseClass {}
class Container<T> where T : BaseClass {}
class Program {
static void Main() {
// why doesn't this work?
Container<BaseClass> obj = new Container<ChildClass>();
}
}
这是故意的吗?如果是,原因是什么?
Is this by design? If it is, what is the reason?
推荐答案
(制作 wiki,以防万一)
(made wiki, in case of dups)
C# (3.0) 不支持列表协变等.C# 4.0 将支持有限 [co|contra]variance,但 仍然不是列表.
C# (3.0) doesn't support covariance of lists etc. C# 4.0 will support limited [co|contra]variance, but still not lists.
问题在于:
Container<BaseClass> obj = new Container<ChildClass>();
我可以:
obj.Add(new SomeOtherSubclass()); // SomeOtherSubclass : BaseClass
可以编译,但不能工作.
which would compile, but not work.
数组支持这种行为,但主要是出于历史原因.
This behaviour is supported for arrays, but largely for historic reasons.
这篇关于C#:没有来自 Class<Child> 的隐式转换到 Class<Base>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文