C#导致DLL动态负载不匹配

时间:2015-08-13 08:12:17

标签: c# .net exception

出于测试目的,

我正在尝试构建一个场景,其中我有两个具有相同名称空间,类和方法名称的dll。

E.g。

DLL1:

namespace SomeNamespace
{
    public class Foo
    {
        public static string Bar()
        {
            return "A";
        }
    }
}

DLL2:

namespace SomeNamespace
{
    public class Foo
    {
        public static string Bar()
        {
            return "B";
        }
    }
}

我试图编写动态调用Foo.Bar()的代码,以获得歧义的异常。

在我的代码中,我特别需要将dll名称作为参数传递,我想避免使用。

        Assembly a = Assembly.LoadFile(dllPath);

        Type t = a.GetType(typeName);

        MethodInfo method = t.GetMethod(methodName);

        var result = new object();

        if (method.IsStatic)
        {
            result = method.Invoke(null, null);
        }

        else
        {
            object instance = Activator.CreateInstance(t);

            result = method.Invoke(instance, null);
        }

有没有办法让这个例外?

1 个答案:

答案 0 :(得分:0)

如果两个程序集具有相同的程序集名称,则可以使用Type.GetType(string),如下所示:https://stackoverflow.com/a/6465096/613130,所以

Type t = Type.GetType("SomeNamespace.Foo,SomeAssembly");

我认为没有.NET方法可以在所有已加载的程序集中搜索Type

相关问题