引用所需的重载泛型方法 [英] referencing desired overloaded generic method

查看:72
本文介绍了引用所需的重载泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给予

public Class Example
{

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

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

}

问题:

  1. 将其称为重载泛型方法"是否正确?
  2. 如何在创建MethodInfo对象时指定任一方法?

  1. Is it correct to call this an "overloaded generic method"?
  2. How can either method be specified in creation of a MethodInfo object?

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

参数4会使编译器不满意

argument 4 causes the compiler much displeasure

推荐答案

我找不到使用GetMethod的方法来完成您想要的事情.但是,您可以获取所有方法并遍历列表,直到找到所需的方法.

I can't find a way of using GetMethod that would do what you want. But you can get all the methods and go through the list until you find the method that you want.

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

Remember you need to call MakeGenericMethod before you can actually use it.

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 });
}

这篇关于引用所需的重载泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆