2016-12-02 9 views
0

ダイナミック型を使用してカスタムクラスをインスタンス化する際に問題があります。しかし、私はintタイプが定義されていない位置にいる動的型インスタンスの作成

var myInstance = new myClass<int>("myHeader"); 

public class myClass<T> 
{ 
    public myClass(String header); 
} 

私は、次のコードを使用している場合は、すべてが正常に動作します: 例、私は次のクラスを持っていますので、ジェネリック型のパラメータから動的にキャストする必要があります。私はこれまで試した何を:私はintを使用することはできません

The type or namespace name 'myType' could not be found (are you missing a using directive or an assembly reference?)

の理由:私は次のエラーを取得するすべての例で

1.

Type myType = typeof(int); 
    var myInstance = new myClass<myType>("myHeader"); 

2.

int myInt = 0; 
    Type myType = myInt.GetType(); 
    var myInstance = new myClass<myType>("myHeader"); 

私は実行時に特定のアセンブリから型をロードしているので、 "in常に "t"を意味する。

+0

あなたは関数がジェネリックにするとちょうど '新しいMyClassの( "myHeader")を行うことができますか;'? –

+0

クォンティックに感謝、これも私を助けました。 – m506

答えて

0

実行時にgenericのリストを作成する場合は、have-toReflectionを使用してください。

int myInt = 0; 
Type myType = myInt.GetType(); 

// make a type of generic list, with the type in myType variable 
Type listType = typeof(List<>).MakeGenericType(myType); 

// init a new generic list 
IList list = (IList) Activator.CreateInstance(listType); 

アップデート1:

int myInt = 0; 
Type myType = myInt.GetType(); 
Type genericClass = typeof(MyClass<>); 
Type constructedClass = genericClass.MakeGenericType(myType); 
String MyParameter = "value"; 
dynamic MyInstance = Activator.CreateInstance(constructedClass, MyParameter); 
+0

ありがとうアリ、補完として、完全なコードの下: int myInt = 0; タイプmyType = myInt.GetType(); タイプgenericClass = typeof(MyClass <>); タイプstructuredClass = genericClass.MakeGenericType(myType); 文字列MyParameter = "value"; ダイナミックMyInstance = Activator.CreateInstance(structuredClass、MyParameter); よろしくお願いいたします。 – m506

+0

@ m506ようこそ。あなたが探していたものがあれば、その答えを受け入れることを忘れないでください。私はポストを更新し、あなたのコードをそこに置いた。 –

関連する問題