C#:从类< Child>没有隐式转换到类< Base> [英] C#: No implict conversion from Class<Child> to Class<Base>

查看:83
本文介绍了C#:从类< Child>没有隐式转换到类< Base>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下片段无法编译。出现以下错误:


无法将类型'Container< ChildClass>'隐式转换为'Container< BaseClass>'



  class BaseClass {} $ b $ class ChildClass:BaseClass {} $ b $ class Container< T> T:BaseClass {} 
class Program {
static void Main(){
//为什么这不起作用?
Container< BaseClass> obj = new Container< ChildClass>();
}
}

这是否由设计决定?如果是这样,原因是什么?

解决方案

b
C#(3.0)不支持列表的协方差等。C#4.0将支持限制 [co | contra]方差,但还没有列出



问题在于:

  Container< BaseClass> obj = new Container< ChildClass>(); 

我可以这样做:

  obj.Add(new SomeOtherSubclass()); // SomeOtherSubclass:BaseClass 

可以编译但不能工作。



数组支持这种行为,但主要是出于历史原因。


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?

解决方案

(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:

Container<BaseClass> obj = new Container<ChildClass>(); 

I could do:

obj.Add(new SomeOtherSubclass()); // SomeOtherSubclass : BaseClass

which would compile, but not work.

This behaviour is supported for arrays, but largely for historic reasons.

这篇关于C#:从类&lt; Child&gt;没有隐式转换到类&lt; Base&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆