5

Is is possible to make the following compile without:

  1. Making IFooCollection generic
  2. Explicitly implementing IFooCollection.Items on FooCollection and performing an explicit cast.

public interface IFoo
{

}

public interface IFooCollection
{
    IEnumerable<IFoo> Items { get; }
}

public class FooCollection<T> : IFooCollection where T : IFoo
{
    public IEnumerable<T> Items { get; set; }
}

I'm happy enough with the second solution (implementing the interface explicitly) but would like to understand why I need to cast T as IFoo when we have a generic constraint specifying that T must implement IFoo.

4

1 回答 1

9

原因如下:

IFooCollection.Items可以包含任何实现IFoo. 所以它可以同时包含FooA, FooB, FooC

FooCollection<FooA>.Items另一方面,只能包含 type 的元素FooA。尝试 castFooBFooCtoFooA会产生一个InvalidCastException虽然 all implement IFoo

于 2012-08-31T11:17:58.293 回答