如何获得类型的类
我需要使用如下方法:
DoSomething();
但我不知道我有哪种类型,只有类型的对象。 如果我只有以下情况,我该如何调用此方法:
Type typeOfGeneric;
如果只将Type指定为Type,则必须构建generics方法,并通过reflection调用它。
Type thisType = this.GetType(); // Get your current class type MethodInfo doSomethingInfo = thisType.GetMethod("DoSomething"); MethodInfo concreteDoSomething = doSomethingInfo.MakeGenericMethod(typeOfGeneric); concreteDoSomething.Invoke(this, null);
你使用reflection(假设DoSomething()
是静态的):
var methodInfo = typeOfGeneric.GetMethod( "DoSomething" ); methodInfo.Invoke( null, null );
编辑:在我写答案时你的问题发生了变化。 上面的代码用于非generics方法,这里是一个generics类:
var constructedType = someType.MakeGenericMethod( typeOfGeneric ); var methodInfo = constructedType.GetMethod( "DoSomething" ); methodInfo.Invoke( null, null );
这里是非generics类的静态generics方法:
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" });