简体   繁体   中英

Simple Covariance doesn't seem to work with c# generics

It looks to me like I am having an understanding problem with covariance in c#. If I have the following classes:

class a {
}

class b : a {
}

class A<T> where T: a {
}

class B<T> : A<T> {
}

class C : A<b> {
}

And now I do:

A<a> t1 = new B<b>();
A<a> t2 = new C();

Neither of those work - but why?? Doesn't this article from Microsoft propose, that exactly this should be working? http://msdn.microsoft.com/de-de/library/dd799517(v=vs.110).aspx

Why isn't this very simple example not working?

Best regards

Covariance works like you describe, but there is one important piece:

A generic class is only covariant if it inherits from an interface marked with the "out" keyword on the covariant generic parameter.

There are a bunch of rules on how you can use this, see MSDN for details.

You aren't inheriting a covariant interface, so your derived assignments will break.

You need something like:

IGeneric<out T>
{
}

class a<T> : IGeneric<T>
{
}

and so on. Your assignments should work as long as it looks like:

IGeneric<Base> = a<Derived>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM