问题
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