C#获取一个通用方法并调用它
示例
假设您有使用通用方法的类。并且您需要通过反射来调用其功能。
public class Sample
{
public void GenericMethod<T>()
{
//...
}
public static void StaticMethod<T>()
{
//...
}
}假设我们要使用字符串类型调用GenericMethod。
Sample sample = new Sample();//或者您可以通过反射获得实例
MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(typeof(string));
generic.Invoke(sample, null);//由于没有参数,我们传递了null对于静态方法,您不需要实例。因此,第一个参数也将为null。
MethodInfo method = typeof(Sample).GetMethod("StaticMethod");
MethodInfo generic = method.MakeGenericMethod(typeof(string));
generic.Invoke(null, null);