如何在C#中使用反射调用重载方法。 AmbiguousMatchException

时间:2020-03-16 15:13:47

标签: c# reflection

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

from pyspark.sql import functions as F
from pyspark.sql import Window

w = Window.partitionBy('year_num').orderBy('week_beg_dt')

business_days_ = df2.withColumn('dates', F.collect_set('week_beg_dt').over(w)) \
                    .groupBy('year_num') \
                    .agg(F.max('dates').alias('dates')) \
                    .collect()

当我同时使用这两种方法时,效果都很好:

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

我只能使用其中一种方法。但是当我在类中同时使用这两种方法时(我需要同时使用两种情况-参数将在没有他的情况下被传递),我会得到一个例外:

AmbiguousMatchException:找到了不明确的匹配项

如何使用两种重载方法?

2 个答案:

答案 0 :(得分:1)

您应该使用方法GetMethod的{​​{3}}重载来找到适当的方法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);
    }
}

以下是使用这种方法的示例:this

答案 1 :(得分:1)

您可以测试 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);
    }
}

我希望这可以帮助您解决问题

相关问题