Joanna Carter [TeamB] <jo****@not.for.spam> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> a écrit dans le message de news:
MP************************@msnews.microsoft.com...
| > I suspected as much, but then I still don't understand why an
| > IList<Observation> can be cast to List<IObservation>.
|
| It can't. It can be cast to List<Observation>, but not
| List<IObservation>.
After posting my latest reply, I now recant and agree with you John. I had
compiled the test code but hadn't run it. Sure enough, it generates an
invalid typecast :-)
I take it I am correct in saying that that you can cast the generic type to
its ancestor/derivative types, but you have to maintain the parameter type
to be absolutely identical ?
Yup.
From the draft of the ECMA spec:
<quote>
No special conversions exist between constructed reference types other
than those described in §15. In particular, unlike array types,
constructed reference types do not exhibit =3Fco-variant=3F conversions..
This means that a type List<B> has no conversion (either implicit or
explicit) to List<A> even if B is derived from A. Likewise, no
conversion exists from List<B> to List<object>.
[Note: The rationale for this is simple: if a conversion to List<A> is
permitted, then apparently, one can store values of type A into the
list. However, this would break the invariant that every object in a
list of type List<B> is always a value of type B, or else unexpected
failures can occur when assigning into collection classes. end note]
</quote>
and
<quote>
A constructed class type has a direct base class, just like a simple
class type. If the generic class declaration does not specify a base
class, the base class is object. If a base class is specified in the
generic class declaration, the base class of the constructed type is
obtained by substituting, for each type-parameter in the base class
declaration, the corresponding type-argument of the constructed type.
</quote>
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too