可能重复:
Calling generic method with a type argument known only at execution time
我有一个通用方法,我希望它在运行时使用已知的Type-Object来调用它。
public class someClass {
public void someGenericMethod<T>()
{
//some Code to Execute
}
public void someMthod()
{
Type objectType = someInstance.getType();
someGenericMethod<objectType>(); //this isn't valid code, but I want to do something like this.
}
}
有没有办法在C#/ .net中执行此操作,还是有解决方法?
答案 0 :(得分:3)
这是可能的,但它很难看:
var method = typeof (someClass).GetMethod("someGenericMethod").MakeGenericMethod(objectType);
method.Invoke(this, null);
答案 1 :(得分:3)
您可以使用反射:
var genericMethod = typeof(someClass).GetMethod("someGenericMethod");
var methodInstance = genericMethod.MakeGenericMethod(objectType);
methodInstance.Invoke(someInstance, null);