IList在c#中使用协方差和逆变,这可能吗?

这有可能吗? (我没有对阵2010年,所以我不能自己尝试,对不起)

public interface IComplexList where TOutput : TInput { public IEnumerator GetEnumerator(); public void Add(TInput item); } public interface IList : IComplexList { } 

如果我做对了,你可以用它来在同一个界面中实际实现协方差和逆变。

不,你不能。 在您的示例中, IList是不变的。 IList需要声明in / out是协变/逆变。 仅通过inheritance一些协变的接口是不可能做到这一点的。

好吧,由于现有的IList类型,您的问题有点令人困惑。 但是,以下编译:

 public interface IComplexList where TOutput : TInput { IEnumerator GetEnumerator(); void Add(TInput item); } public interface ISimpleList : IComplexList { } 

您甚至可以更改它以扩展IEnumerable

 public interface IComplexList : IEnumerable where TOutput : TInput { void Add(TInput item); } public interface ISimpleList : IComplexList { } 

索引器很棘手,因为你需要涉及不同的类型。 你可以这样做:

 TOutput Get(int index); void Set(int index, TInput item); 

然后将索引器放入ISimpleList而不是当然……

这不会让你使用ISimpleList ,因为你基本上强迫TInput = TOutput。

另一种方法是从输出中分离出输入:

 public interface IReadableList : IEnumerable { T Get(int index); } public interface IWritableList { void Add(T item); void Set(int index, T item); } public interface IMyList : IReadableList, IWritableList {} 

然后你可以写:

 public void Foo(IWritableList x) { ... } IMyList objects = new MyList(); Foo(objects); 

反之亦然, IReadableList 。 换句话说,你可以单独允许每一方的差异,但你永远不会得到双方的差异。

如果读写属性的实现也被认为是只读属性的实现,则可以通过使IList(of T)派生自IReadableList(Out T)和IAddableList(可以)来添加List协方差和逆变的有用forms。在T)。 如果这些接口只包含在IList(Of T)中定义的成员,那么实现IList(Of T)的代码将自动实现其他成员。 不幸的是,要使IReadableList具有协变性,它必须具有只读索引器属性; 无法替换IList中读写属性的实现。 让IList(Of T)从可用的IReadableList(Of Out T)inheritance将因此破坏IList(Of T)的所有实现。