将List <T>(其中T:IBar)转换为ICollection <IBar>失败

Kon*_*ski 1 c# casting interface list icollection

我有classT,实施interfaceIBar.

我有一个list类型的变量List<T>.

提高我对语言理解的两个问题:

  • 为什么这不起作用?

    var foo = (ICollection <IBar>)list; // fails!

  • 如何解决它(如果可能的话)?

Hei*_*nzi 5

为什么这不起作用?: var foo = (ICollection <IBar>)list;

让我们说T = Foo,还有第二堂课Foo2 : IBar.

然后你可以这样继续:

var foolist = (ICollection <IBar>)list;
foolist.Add(new Foo2());  // compiles, since Foo2 also implements IBar
Run Code Online (Sandbox Code Playgroud)

重击!您在运行时遇到类型违规,因为您尝试将a添加Foo2到a List<Foo>.

为了避免这种情况,ICollection<Foo>不是的一个亚型ICollection<IBar>,即使Foo是一个亚型IBar.这背后的理论是共同和逆转.