繁体   English   中英

c#中如何使用反射调用重载方法。 歧义匹配异常

[英]How to call the overloaded method using reflection in c#. AmbiguousMatchException

我尝试使用反射调用重载方法。

public void SomeMethod(string param)
{
    param = param.Length > 0 ? param : null;
    Type thisType = this.GetType();
    MethodInfo theMethod = thisType.GetMethod("methodName", BindingFlags.NonPublic | BindingFlags.Instance);
    theMethod.Invoke(this, param);
}

当我使用这两种方法之一时,一切正常:

//works well if param = "" (null)
private void methodName(){
}

//works well if param = "anystring"
private void methodName(string parameter){
}

我只能使用其中一种方法。 但是,当我在类中使用这两种方法时(我需要同时使用这两种情况 - 将传递 param 而没有他)我得到异常:

AmbiguousMatchException:找到不明确的匹配

如何使用这两种重载方法?

您应该使用方法的重载GetMethod找到合适的方法methodName 此重载考虑了方法参数及其类型的数量。 使用这个重载方法SomeMethod应该像这样重写:

public void SomeMethod(string param)
{
    Type thisType = GetType();

    if (!string.IsNullOrEmpty(param))
    {
        // Find and invoke method with one argument.
        MethodInfo theMethod = thisType.GetMethod("methodName", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(string)}, null);
        theMethod.Invoke(this, new object[] {param});
    }
    else
    {
        // Find and invoke method without arguments.
        MethodInfo theMethod = thisType.GetMethod("methodName", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
        theMethod.Invoke(this, null);
    }
}

以下是使用此方法的示例: https : //dotnetfiddle.net/efK1nt

您可以测试methodName 的参数数量,如果等于或大于0 ,如下代码:

public void SomeMethod(string param)
{
    Type thisType = this.GetType();

    if (!string.IsNullOrEmpty(param))
    {
        MethodInfo theMethod1 = thisType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
        .FirstOrDefault(m => m.Name == "methodName" && m.GetParameters().Count() > 0);

        theMethod1.Invoke(this, new[] { param });
    }
    else
    {
        MethodInfo theMethod2 = thisType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
        .FirstOrDefault(m => m.Name == "methodName" && m.GetParameters().Count() == 0);

        theMethod2.Invoke(this, null);
    }
}

我希望这能帮助您解决问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM