You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:18:03