2

その場合のエラーを理解するのを手伝ってもらえますか?

public interface IGeneralInterface
{
}


public class A : IGeneralInterface
{
}

public class B : IGeneralInterface
{
}

public class SomeClass<TGenericType> where TGenericType : IGeneralInterface
{
    private TGenericType internalValue;

    public SomeClass(TGenericType InitValue)
    {
        internalValue = InitValue;
    }

    public TGenericType CreateAnother()
    {
       TGenericType val1 = new B();   //Error here: class B() could not be converted to TGenericType
       return val1;
    }
}

SomeClass<T>asをビルドしても

SomeClass<IGeneralInterface> someClass = new SomeClass<IGeneralInterface>();

すべての(?)ケースを含めるために明示的にベースインターフェイスを渡しますが、それでもエラーがスローされます

4

3 に答える 3

3

変化する

 TGenericType val1 = new B();   //Error here: class B() could not be converted to TGenericType

  IGeneralInterface val1 = new B();   

エラーの原因となっているTypeCastIGeneralInterfaceをしようとしています。TGenericType

TGenericTypeISpecificInterface継承しないものから継承するなど、他の制約を持つことができますB。この場合、割り当ては無効になります。

例:

public class SomeClass< TGenericType> where TGenericType : IGeneralInterface, ISpecificInterface
TGenericType val1 = new B(); // TGenericType should be ISpecificInterface also, B is not.

上記を実行します。IGenericInterfaceよりも常に具体的である必要がありますTGenericType

 public class SomeClass <IGenericInterface> 

または、キーワードを使用isして、オブジェクトが割り当て可能かどうかを調べてからTGenericType、キャストを使用することもできます。

TGenericType val1 = default(TGenericType);
var val = new B();
if ( val is TGenericType)
{
  val1 = (TGenericType)val;
}

EDIT以下のコメントについて

実行時にどのように追加の要件を持つことができますか? ここにリストされているコンパイラに入れるものはすべて

CreateAnother()BジェネリックではないType のインスタンスを作成します。以下の例を見てください

SomeClass<C> c = new SomeClass<C();
C another = c.CreateAnother(); // C is not assignable from B. (C is below). But It would be valid, if compiler did not flag the error

public class C : IGeneralInterface, IDisposable
{
}
于 2013-01-01T12:22:26.037 に答える
1

new B()なぜ aが に変換可能であるべきだと思いますTGenericTypeか? 知られている唯一のことTGenericTypeは、それがインターフェースを実装していることです。

例として、new B()を type に変換することはできませんA

何を取得しようとしているのかわかりませんが、一般的な制約を次のように変更できます。

public class SomeClass<TGenericType>
    where TGenericType : class, IGeneralInterface, new()

new TGenericType()次に、 create メソッド内で言っても問題ありません。

ただし、SomeClass<IGeneralInterface>そのインターフェイスにはアクセス可能なパラメーターなしのインスタンス コンストラクターがないため、型を使用できなくなります (もちろん、コンストラクターを持つインターフェイスはありません)。

于 2013-01-01T12:33:51.803 に答える
0

コードの問題は、変数を宣言していることです

val1 

タイプの

TGenericType

次に、別のタイプのオブジェクトによってインスタンス化しようとします。

クラスのジェネリック型が継承階層になければならないという条件を述べたとしても、IGeneralInterfaceそれらはコンパイラーによって異なります。この設定では、明示的なキャストを使用する必要があると思います。

于 2013-01-01T12:29:48.260 に答える