我有以下扩展类:
public static class KeyValueConfigurationCollectionExtensions
{
public static string Get(this KeyValueConfigurationCollection collection, string key)
{
return collection[key].Value;
}
public static T Get<T>(this KeyValueConfigurationCollection collection, string key)
{
return (T)Convert.ChangeType(collection[key].Value, typeof(T));
}
}
有人能告诉我如何通过反射获得泛型方法(上例中的第二个)的重载?这行代码在运行时抛出AmbiguousMatchException
:
MethodInfo method = typeof(KeyValueConfigurationCollectionExtensions).GetMethod("Get");
我知道GetMethod
函数存在重载,我可以在其中指定参数,但在这种情况下,两种方法的参数相同。如果我需要它来进行验收测试,那就很好解决。
对我来说最简单的解决方案是:
MethodInfo methodInfo = typeof(KeyValueConfigurationCollectionExtensions)
.GetMethods().Single(method => method.Name == "Get" && method.IsGenericMethod);
谢谢你们快速回答并祝你好日子:)
答案 0 :(得分:2)
MethodInfo
上还定义了IsGenericMethod
:
MethodInfo method = typeof(KeyValueConfigurationCollectionExtensions).GetMethods()
.FirstOrDefault(x => g.Name == "Get" && x.IsGenericMethod);
答案 1 :(得分:1)
您需要通过调用GetGenericArguments()来获取具有泛型参数的方法,如本示例中的Linqpad:
void Main()
{
var method = typeof(KeyValueConfigurationCollectionExtensions)
.GetMethods()
.Where(m => m.Name == "Get")
.Where(m => m.GetGenericArguments().Any())
.Single()
.Dump();
}
// Define other methods and classes here
public static class KeyValueConfigurationCollectionExtensions
{
public static string Get(this KeyValueConfigurationCollection collection, string key)
{
return collection[key].Value;
}
public static T Get<T>(this KeyValueConfigurationCollection collection, string key)
{
return (T)Convert.ChangeType(collection[key].Value, typeof(T));
}
}
public class KeyValueConfigurationCollection
{
public KeyValuePair<string, string> this [string key]
{
get
{
return new KeyValuePair<string, string>("KEY: " + key, "VALUE: Hi!");
}
}
}
答案 2 :(得分:0)
如果你有重载方法,那么你必须使用带有linq的GetMethods方法:
MethodInfo method = typeof(KeyValueConfigurationCollectionExtensions).GetMethods().FirstOrDefault(m=>m.Name=="Get"&&m.ContainsGenericParameters==true).MakeGenericMethod(new Type[]{yourtype});