문제

I am trying to create an instance of a generic class but my Type T of the generic class, i have gone through this link http://msdn.microsoft.com/en-us/library/w3f99sx1(v=vs.110).aspx but i couldn't find what i was looking for

i have this code

public class MyClass<T>
{
    public T prop { get; set; } 
}

and i have the type stored in string the type

string typeString = "System.String";

now i want to use this type in myclass this way

Type xt = new Type.GetType(typeString);
MyClass<xt> obj = new MyClass<xt>();

but that just unidentified type xt so what do i do!

도움이 되었습니까?

해결책

The section Constructing an Instance of a Generic Type in the link provided covers this exact case.

In your case you would need write

Type typeArgument = Type.GetType(typestring);
Type constructed = typeof(MyClass<>).MakeGenericType(typeArgument);
object instance = Activator.CreateInstance(constructed);

However, the use cases of this techniques are far from common. You should try as much as possible to provide type information at compile-time. That is, try not to rely on Reflection to create your objects. Generics methods are especially useful for such cases.

다른 팁

The method Type.GetType(someString) gets the type at runtime, but generics class must be evaluated at compiled time. Between the <> symbols you need to specify the type itself and not an instance of the object Type. Something like this must work:

MyClass<String> obj = new MyClass<String>();

Thanks,

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top