gpt4 book ai didi

c# - 在 C# 中通过反射获取扩展方法的泛型重载

转载 作者:行者123 更新时间:2023-11-30 21:37:57 49 4
gpt4 key购买 nike

我有以下扩展类:

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

感谢你们的快速回答,祝你们有美好的一天:)

最佳答案

还有 IsGenericMethodMethodInfo 上定义:

MethodInfo method = typeof(KeyValueConfigurationCollectionExtensions).GetMethods()
.FirstOrDefault(x => g.Name == "Get" && x.IsGenericMethod);

关于c# - 在 C# 中通过反射获取扩展方法的泛型重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507405/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com