Covariance and contravariance
May be my question is dumb but here it is.
Is Covariance and contravariance开发者_C百科 only applicables for delegates in c#?
Can we have Covariance and contravariance in normal class hierarchies?
Is Covariance and contravariance only applicables for delegates in c#?
Not quite; the language-level variance can also apply to interfaces, for example IEnumerable<out T>
(likewise in
is fine too).
I should also note that arrays of reference-types are also covariant:
string[] orig = {"abc","def"};
object[] sameArray = orig;
Can we have Covariance and contravariance in normal class hierarchies?
No; it does not apply to classes / structs (although you can of course implement a covariant interface, and coerce to that interface).
精彩评论