问题
I try to call overloaded method using reflection.
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);
}
When I use one of both method all works well:
//works well if param = "" (null)
private void methodName(){
}
//works well if param = "anystring"
private void methodName(string parameter){
}
I can use only one of those methods. But when I use both methods in the class (I need to use both cases - when param will be passed and without him) I get the exception:
AmbiguousMatchException: Ambiguous match found
How to can I use both overloaded methods?
回答1:
You should use this overload of the method GetMethod to find appropriate method methodName. This overload takes to account number of method arguments and its types. Using this overload method SomeMethod should be rewritten like this:
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);
}
}
Here is a sample of using this approach: https://dotnetfiddle.net/efK1nt.
回答2:
You can test on parameters number of methodName, if is equal or greater than 0, like the following code :
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);
}
}
I hope this will help you fix the issue
来源:https://stackoverflow.com/questions/60708539/how-to-call-the-overloaded-method-using-reflection-in-c-ambiguousmatchexceptio