避免出现 AmbiguousMethod 异常,可以通过在 GetMethod 方法中指定参数列表来明确选择要获取的方法。但是即使添加了参数列表,GetMethod 仍然返回 null 的原因可能是参数列表与方法签名不匹配。
下面是一个使用反射获取方法并避免出现 AmbiguousMethod 异常的示例代码:
using System;
using System.Reflection;
public class MyClass
{
public void MyMethod(int param)
{
Console.WriteLine("MyMethod(int param)");
}
public void MyMethod(string param)
{
Console.WriteLine("MyMethod(string param)");
}
}
public class Program
{
public static void Main()
{
Type type = typeof(MyClass);
MethodInfo method = type.GetMethod("MyMethod", new Type[] { typeof(int) });
if (method != null)
{
Console.WriteLine("Found method: " + method.Name);
// 进一步处理方法调用
}
else
{
Console.WriteLine("Method not found");
}
}
}
在上面的示例中,我们定义了一个 MyClass 类,包含了两个重载的 MyMethod 方法,一个接受 int 参数,另一个接受 string 参数。
在 Main 方法中,我们使用 typeof(MyClass) 获取 MyClass 的 Type 对象。然后,我们使用 GetMethod 方法获取名为 "MyMethod" 的方法,并指定参数列表为一个 int 类型的数组。
如果找到了匹配的方法,GetMethod 方法会返回该方法的 MethodInfo 对象,我们可以进一步处理方法调用。如果没有找到匹配的方法,GetMethod 方法会返回 null。
通过明确指定参数列表,我们可以避免出现 AmbiguousMethod 异常,并确保获取到我们想要的方法。