C# Generic Class Type parameter (cannot implicitly convert)

无人久伴 提交于 2019-12-31 02:49:07

问题


Scenario:

class A { }

class B : A { }

class C<T> where T: A { }

Question

Why cant C<A> = C<B> when B is a subclass of A? it throws the "cannot implicitly convert" error

Thanks

--UPDATE-- can i create an implicit method for that C<A> would recognize C<B>?


回答1:


Use co-variant if you need to do this, and because co-variant just work only with interface and delegate, so define an interface with the magic word out instead of class:

interface IC<out T> where T : A
{
}

So, you can assign like you want:

class CA : IC<A>
{}

class CB : IC<B>
{ }

IC<A> x = new CA();
IC<B> y = new CB();

x = y;



回答2:


Why cant C<A> = C<B> when B is a subclass of A? B is subclass of A, but C<B> not a subclass of C<A>. There is no assignment compatibility between C<B> and C<A>.




回答3:


Because C<A> is not C<B>

The thing is; if you could do

C<A> myA = new C<B>();
myA.Add(new A());

You'd have a problem, since B is A, but not A is B




回答4:


What you are asking for is Covariance and Contravariance in Generics which is only applicaple for interfaces and delegates. You can check this

You can do the following in Framework >= 4:

interface IC<out T> where T : A

class C<T> : IC<T>  where T : A

IC<A> ica = new C<B>();

For your case you should extract an interface for class C



来源:https://stackoverflow.com/questions/14747476/c-sharp-generic-class-type-parameter-cannot-implicitly-convert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!