如何使用反射调用泛型方法?
当类型参数在编译时未知,而是在运行时动态获取时,调用通用方法的最佳方法是什么?
考虑下面的示例代码-
内部Example()方法,什么是最简洁的方式来调用GenericMethod<T>()使用Type存储在myType变量?
public class Sample{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);
        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work
        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }
    public void GenericMethod<T>()
    {
        // ...
    }
    public static void StaticMethod<T>()
    {
        //...
    }
}
回答:
您需要使用反射来使方法开始,然后通过为MakeGenericMethod提供类型参数来“构造”它:
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
对于静态方法,将null作为第一个参数传递给Invoke。这与泛型方法无关,只是正常的反映。
如前所述,从C#4开始,使用dynamic-在您可以使用类型推断的情况下,当然很多事情都比较简单。在类型推断不可用的情况下(例如问题中的确切示例),它无济于事。
以上是 如何使用反射调用泛型方法? 的全部内容, 来源链接: utcz.com/qa/422281.html







