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

瓦伦丁·赫鲁兹茨基

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章