试想像这样的类型(C#):

public interface IAmGeneric<T>
{
   void SoAmI<T1>(T one, T1 two);
}

鉴于我已经从类型的开放通用版本(MethodInfo)和以下数组中打开了通用IAmGeneric<>.SoAmI<>()
new[] { typeof(int), typeof(string) }'

我正在寻找性能良好且可靠的方式来获取MethodInfo的封闭版本,如下所示:
IAmGeneric<int>.SoAmI<string>()

更新:

可靠的是,我的意思是它应该处理方法不是公共(public)的,有十几个重载,使用基本类型的泛型参数,而不仅仅是其直接接口(interface)等的情况。

最佳答案

像这样吗?不确定您要查找的是什么,也许在您的问题上进行扩展……这肯定需要添加一些检查(例如检查声明类型是否为泛型/方法是否为泛型等)

var method = typeof(IAmGeneric<>).GetMethod("SoAmI");
var types = new[] { typeof(int), typeof(string) };


var methodTypeParams = method.GetGenericArguments();
var fullType = method.DeclaringType.MakeGenericType(types.Take(types.Length - methodTypeParams.Length).ToArray());
var fullMethod = fullType.GetMethod(method.Name).MakeGenericMethod(types.Skip(types.Length - methodTypeParams.Length).ToArray());

10-06 09:54
查看更多