C#:没有来自 Class的隐式转换 到类
以下代码片段无法编译。 出现以下错误:
无法隐式转换类型“Container
” 到“容器 ”
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>();
}
}
这是设计使然吗? 如果是,原因是什么?
Following snippet wouldn't compile. With following error:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(制作维基,以防重复)
C# (3.0) 不支持列表的协方差等。C# 4.0 将支持有限 [co|contra]方差,但是 仍然没有列出。
问题是:
我可以这样做:
它可以编译,但不起作用。
数组支持此行为,但主要是出于历史原因。
(made wiki, in case of dups)
C# (3.0) doesn't support covariance of lists etc. C# 4.0 will support limited [co|contra]variance, but still not lists.
The problem is that with:
I could do:
which would compile, but not work.
This behaviour is supported for arrays, but largely for historic reasons.
哟,
如果您想要有关 C# 协变/逆变的杀手级文章,请查看 eric lippert 博客“编码中的精彩冒险”。 首先,这是我最喜欢的博客的名称,其次,eric 写了关于 (co|contra)variance 的最佳文章序列:
http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance- in-c-part-one.aspx
这和绝命毒师一样好。
Yo,
If you want the killer article on covariance/contravariance on C#, check out the eric lippert blog, "fabulous adventures in coding". First, this is my favortie blog's name, and second eric wrote the best sequence of articles on (co|contra)variance:
http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx
This is as good as Breaking Bad.
这就是所谓的协变/逆变,从 C# 3.0 开始不可用。 它在 C# 4.0 中有些可用。 以下是一些信息:
http: //reddevnews.com/articles/2009/05/01/generic-covariance-and-contravariance-in-c-40.aspx
This is what's knows as covariance / contravariance which isn't available as of C# 3.0. It will be somewhat available in C# 4.0. Here's some info:
http://reddevnews.com/articles/2009/05/01/generic-covariance-and-contravariance-in-c-40.aspx
有一种非常常见的误解,认为
MyClass
继承自 <代码>MyClassThere is a very common mis-conception that
MyClass<Child>
inherits fromMyClass<Base>
.