开发者

Casting a List<T> (where T : IBar) to ICollection<IBar> fails

开发者 https://www.devze.com 2023-04-09 02:16 出处:网络
I have classT, impl开发者_StackOverflowementing interfaceIBar. I have a variable list of type List<T>.

I have classT, impl开发者_StackOverflowementing interfaceIBar.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消