引用所需的重载泛型方法

2024-04-01

given

public Class Example
{

public static void Foo< T>(int ID){}

public static void Foo< T,U>(int ID){}

}

问题:

  1. 称其为“重载通用方法”是否正确?
  2. 如何在创建 MethodInfo 对象时指定任一方法?

    Type exampleType = Type.GetType("fullyqualifiednameOfExample, namespaceOfExample");
    MethodInfo mi = exampleType.GetMethod("Foo", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof(Type), typeof(Type) }, null);
    

参数 4 导致编译器非常不满


我找不到一种使用 GetMethod 来完成您想要的操作的方法。但您可以获取所有方法并浏览列表,直到找到所需的方法。

请记住,您需要先调用 MakeGenericMethod,然后才能实际使用它。

var allMethods = typeof (Example).GetMethods(BindingFlags.Public | BindingFlags.Static);
MethodInfo foundMi = allMethods.FirstOrDefault(
    mi => mi.Name == "Foo" && mi.GetGenericArguments().Count() == 2);
if (foundMi != null)
{
    MethodInfo closedMi = foundMi.MakeGenericMethod(new Type[] {typeof (int), typeof (string)});
    Example example= new Example();
    closedMi.Invoke(example, new object[] { 5 });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

引用所需的重载泛型方法 的相关文章

随机推荐