さて、あなたの質問は、既存の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
。言い換えれば、各側の分散を個別に許可しますが、2 つの側の分散を一緒に取得することはありません。