.NET反射调用重载方法报AmbiguousMatchException,如何调用指定非泛型Call方法
问题原因与解决方案
你遇到的AmbiguousMatchException异常是因为Doub类中存在两个同名无参的Call重载:一个是非泛型方法,一个是未绑定泛型参数的泛型方法定义,InvokeMember默认无法自动区分这两个重载,因此抛出匹配模糊错误。
正确实现方式
优先通过手动筛选MethodInfo的方式精准定位目标方法,再执行调用,同时注意Call是实例方法,调用时需要传入类实例,完整代码如下:
using System.Reflection; using System.Collections.ObjectModel; class Program { static void Main(string[] args) { Type doubType = typeof(Doub); // 精准筛选非泛型、无参的公共实例Call方法 MethodInfo nonGenericCallMethod = doubType.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => m.Name == "Call" && !m.IsGenericMethod && m.GetParameters().Length == 0) .Single(); // 创建Doub类实例,实例方法调用必须传入实例对象 object doubInstance = Activator.CreateInstance(doubType); // 执行方法调用 object result = nonGenericCallMethod.Invoke(doubInstance, null); } } public class Doub { public Collection<string> Call() { Collection<string> collection = new Collection<string>(); return collection; } public Collection<T> Call<T>() { Collection<T> collection = new Collection<T>(); return collection; } }
关键筛选逻辑说明
!m.IsGenericMethod:排除泛型版本的Call方法,确保只匹配非泛型重载m.GetParameters().Length == 0:确认是无参重载,后续如果新增其他带参同名方法也可以兼容匹配
内容的提问来源于stack exchange,提问作者KirillMamontov
相关产品推荐
相关产品推荐

