2

私はいくつかのインターフェースMyClass<T>であるクラスを持っています:T

class MyClass<T> where T: IMyInterface

MyClassの実装を使用して拡張するいくつかのクラスを作成IMyInterfaceしました。たとえば、次のようになります。

class MySecondClass : MyClass<MyInterfaceImplementation>

MySecondClass型を持つ変数への代入インスタンスがMyClass<IMyInterface>許可されないのはなぜですか?

MyClass<IMyInterface> x = new MySecondClass()

暗黙の変換を追加すると:

public static implicit operator MyClass<IMyInterface>(MySecondClass c) {
    return c;
}

それは働き始めます。

4

3 に答える 3

2

必要なことを行うには、キーワード を使用して型パラメーターTが共変であることを宣言する必要があります (MSDNの Generics の Covariance and Contravariance を参照してください)。 共分散と反分散はインターフェイスでのみ定義できるため、コードを少し変更する必要があります。out

interface IMyInterface { 
}

// note that this one is an interface now
interface IMyClass<out T> where T : IMyInterface { 
}

class MyInterfaceImplementation : IMyInterface { 
}

class MySecondClass : IMyClass<MyInterfaceImplementation> { 
}

class Program {
    static void Main(string[] args) {
        IMyClass<IMyInterface> x = new MySecondClass();
    }
}
于 2013-11-04T12:11:38.503 に答える
1

MyClass<IMyInterface>また、MySecondClass2 つの異なるクラスとコンパイラは、ある型のオブジェクトを別の型に暗黙的に変換することはできません。

さらに、これら2つのクラスはSystem.Object共通の基本クラスとしてのみ持っています

于 2013-11-04T12:00:06.143 に答える