访问dll时发现模糊匹配

Pan*_*lhe 4 c# reflection overloading dllimport

我正在尝试在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();
Run Code Online (Sandbox Code Playgroud)

我调用的方法(即Foo),不接受任何参数,它是一个重载方法.那是我出错的地方还是其他地方?

有没有其他方法可以调用不接受任何参数的方法?我试过这里发布的解决方案,但它没有用.

lup*_*pok 11

如果存在重载并且您想要调用不带参数的方法,则这是正确的解决方案:

MethodInfo mi = obj.GetType().GetMethod("Foo", new Type[] { });
Run Code Online (Sandbox Code Playgroud)


Tob*_*ias 8

Type.GetMethod(string methodName)如果有多个具有指定名称的方法,则该方法抛出您提到的异常(请参阅此MSDN主题).正如Foo你所说的那样重载,我怀疑Foo同一个DLL中有多个方法.如果你有例如方法:

IList<string> Foo()

IList<string> Foo(object someParameter)
Run Code Online (Sandbox Code Playgroud)

该方法GetMethod(string methodName)无法确定您想拥有哪一个.在这种情况下,您应该使用该方法GetMethods并自己确定正确的方法.