IList<T>
好吧,由于现有类型,您的问题有点令人困惑。但是,以下内容会编译:
public interface IComplexList<out TOutput, in TInput> where TOutput : TInput
{
IEnumerator<TOutput> GetEnumerator();
void Add(TInput item);
}
public interface ISimpleList<T> : IComplexList<T, T>
{
}
您甚至可以将其更改为扩展IEnumerable<TOutput>
:
public interface IComplexList<out TOutput, in TInput>
: IEnumerable<TOutput>
where TOutput : TInput
{
void Add(TInput item);
}
public interface ISimpleList<T> : IComplexList<T, T>
{
}
索引器很棘手,因为您需要涉及不同的类型。你可以这样做:
TOutput Get(int index);
void Set(int index, TInput item);
然后将索引器放入ISimpleList<T>
而不是...
但是,这并不允许您使用ISimpleList<T>
变体,因为您基本上已经强制 TInput=TOutput。
另一种方法是将输入与输出分开:
public interface IReadableList<out T> : IEnumerable<T>
{
T Get(int index);
}
public interface IWritableList<in T>
{
void Add(T item);
void Set(int index, T item);
}
public interface IMyList<T> : IReadableList<T>, IWritableList<T> {}
然后你可以写:
public void Foo(IWritableList<string> x) { ... }
IMyList<object> objects = new MyList<object>();
Foo(objects);
反之亦然IReadableList
。换句话说,你允许每一边单独出现差异,但你永远不会得到两侧的差异。