[英]Getting generic overload by reflection for extension method in C#
我有以下擴展程序類:
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);
謝謝你們的快速解答,並祝您有美好的一天:)
還有在MethodInfo
定義的IsGenericMethod
:
MethodInfo method = typeof(KeyValueConfigurationCollectionExtensions).GetMethods()
.FirstOrDefault(x => g.Name == "Get" && x.IsGenericMethod);
您需要通過調用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!");
}
}
}
如果您有重載的方法,則必須對linq使用GetMethods方法:
MethodInfo method = typeof(KeyValueConfigurationCollectionExtensions).GetMethods().FirstOrDefault(m=>m.Name=="Get"&&m.ContainsGenericParameters==true).MakeGenericMethod(new Type[]{yourtype});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.