开发者

How to get class of type [duplicate]

This question already has answers here: How do I use reflect开发者_Go百科ion to call a generic method? (8 answers) Closed 8 years ago.

I need to use method like:

DoSomething<(T)>();

But i don't know which Type i have, only object of class Type. How can i call this method if I have only:

Type typeOfGeneric;


You use reflection (assuming DoSomething() is static):

var methodInfo = typeOfGeneric.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );

EDIT: Your question changes while I wrote the answer. The above code is for a non-generic method, here it is for a generic class:

var constructedType = someType.MakeGenericMethod( typeOfGeneric );
var methodInfo = constructedType.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );

And here it is for a static generic method on a non-generic class:

var typeOfClass = typeof(ClassWithGenericStaticMethod);

MethodInfo methodInfo = typeOfClass.GetMethod("DoSomething",   
    System.Reflection.BindingFlags.Static | BindingFlags.Public);

MethodInfo genericMethodInfo = 
    methodInfo.MakeGenericMethod(new Type[] { typeOfGeneric });

genericMethodInfo.Invoke(null, new object[] { "hello" });


If you only have a Type specified as a Type, you'd have to build the generic method, and call it via reflection.

Type thisType = this.GetType(); // Get your current class type
MethodInfo doSomethingInfo = thisType.GetMethod("DoSomething");

MethodInfo concreteDoSomething = doSomethingInfo.MakeGenericMethod(typeOfGeneric);
concreteDoSomething.Invoke(this, null);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜