Casting a List<T> (where T : IBar) to ICollection<IBar> fails
I have class
T
, impl开发者_StackOverflowementing interface
IBar
.
I have a variable list
of type List<T>
.
Two questions for enhancing my understanding of the language:
Why doesn't this work?
var foo = (ICollection <IBar>)list; // fails!
How to work around it (if possible)?
Why doesn't this work?:
var foo = (ICollection <IBar>)list;
Let's say T = Foo
and there's a second class Foo2 : IBar
.
Then you could continue like this:
var foolist = (ICollection <IBar>)list;
foolist.Add(new Foo2()); // compiles, since Foo2 also implements IBar
Wham! You have a type violation at runtime, since you tried to add a Foo2
to a List<Foo>
.
To avoid this, ICollection<Foo>
is not a subtype of ICollection<IBar>
, even though Foo
is a subtype of IBar
. The theory behind this is co- and contravariance.
精彩评论