如何获得类型的类

如何获得类型的类

问题描述:

我需要使用以下方法:

I need to use method like:

DoSomething<(T)>();

但是我不知道我有哪些类型,只有类Type的对象。如果我只有以下方法,我该如何调用此方法:

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;


如果您只有指定为Type的Type,您必须构建泛型方法,并通过反射来调用它。

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);