我需要使用类似以下方法:
DoSomething<(T)>();
但我不知道我有哪种类型,只有Type类的对象。如果我只有这个,我该如何调用这个方法:
Type typeOfGeneric;
DoSomething()
是静态的):var methodInfo = typeOfGeneric.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );
编辑:当我回答时,您的问题已经发生了变化。上面的代码是非泛型方法的,这里是泛型类的:
var constructedType = someType.MakeGenericMethod( typeOfGeneric );
var methodInfo = constructedType.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );
这是一个非泛型类上的静态泛型方法:
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" });
Type thisType = this.GetType(); // Get your current class type
MethodInfo doSomethingInfo = thisType.GetMethod("DoSomething");
MethodInfo concreteDoSomething = doSomethingInfo.MakeGenericMethod(typeOfGeneric);
concreteDoSomething.Invoke(this, null);