我正在尝试在dll中加载一个函数。dll被加载,但就在调用函数的地方,我得到了一个异常。
二义性匹配
这是代码片段。
Assembly dll = Assembly.LoadFrom(DLLPATH);
if (dll != null)
{
    Type Tp = dll.GetType("ABCD.FooClass");
    if (Tp != null)
    {
        Object obj = Activator.CreateInstance(Tp);
        if (obj != null)
        {                            
            List = (List<String>)obj.GetType().GetMethod("Foo").Invoke(obj, null);
        }
        else
        {
            Console.WriteLine("obj is null");
        }
    }
    Console.WriteLine("Type is null");
}
else
    Console.WriteLine("Dll is not loaded");
Console.ReadKey();我正在调用的方法(即Foo),不接受任何参数,它是一个重载的方法。那是我出问题的地方还是别的地方?
是否有另一种方法来调用这些不接受任何参数的方法?我尝试过发布这里的解决方案,但它不起作用。
发布于 2013-03-06 08:27:00
如果有多个具有指定名称的方法(请参阅Type.GetMethod(string methodName) ),则方法此MSDN主题抛出您提到的异常。正如您所说,Foo是一种重载,因此我怀疑在同一个DLL中存在多个Foo方法。例如,如果您有以下方法:
IList<string> Foo()
IList<string> Foo(object someParameter)方法GetMethod(string methodName)无法确定您想要的是哪一个。在这种情况下,您应该使用GetMethods方法并自行确定正确的方法。
发布于 2013-12-31 19:07:41
如果存在重载,并且要调用不带参数的方法,则这是正确的解决方案:
MethodInfo mi = obj.GetType().GetMethod("Foo", new Type[] { });发布于 2013-03-06 10:11:35
谢谢你们的帮助!
正如我告诉过您的,我调用的方法(即FOO)是重载的。我想我没有正确地使用GetMethod()。现在,我找到了一个使用GetMethods()函数的解决方案。
我用下面的方式修改了我的代码,它起了作用。
Assembly dll = Assembly.LoadFrom(DLLPATH);
if (dll != null)
{
   Type Tp = dll.GetType("ABCD.FooClass");
   if (Tp != null)
   {
      Object obj = Activator.CreateInstance(Tp);
      if (obj != null)
      {                            
         MethodInfo[] AllMethods = obj.GetType().GetMethods();
         MethodInfo Found = AllMethods.FirstOrDefault(mi => mi.Name == "Foo" && mi.GetParameters().Count() == 0);
         if (Found != null)
             List = (List<String>)Found.Invoke(obj, null);           
      }
      else
        Console.WriteLine("obj is null");       
   }
    else
     Console.WriteLine("Type is null");
 }
  else
     Console.WriteLine("Dll is not loaded");https://stackoverflow.com/questions/15241865
复制相似问题