我有一个 .net Winform 应用程序,它试图动态加载程序集但收到 ReflectionTypeLoadException 异常
该应用程序包括对 P.DLL 和 C.DLL 的两个引用(代码在下面)然后动态加载 SI.DLL(要加载的代码在下面)
这是我的问题开始之前的代码
P.DLL 包含这个
public interface iP
{
string Version { get; }
}
public class P : iP
{
public P()
{
Version = "4.0";
}
#region iP Implementation
public string Version { get; private set; }
#endregion
}
C.DLL 包含这个
//
// C.DLL
//
public interface iC : iP
{
// no interface changes here
}
public class C : P, iC
{
public C()
{
// this class does stuff but is irrelevant to problem except it is the inheritance chain
}
}
SI.DLL 包含这个
//
// SI.DLL
//
public interface iSI : iC
{
// no interface changes here
}
public class SI_Engine : C, iSI
{
public SI_Engine()
{
// this is the object in the SI.DLL assembly that I am trying to load
}
}
所以本质上 SI (interface iSI) 派生自 C (interface iC) 派生自 P (interface iP)
SI (iSI) : C (iC) : P (iP)
所以用上面的代码,我可以动态加载SI.DLL,没有问题。
这是我的应用程序中动态加载 SI.DLL 的代码
下面是调用加载器的代码:
bool bLoaded = false;
iC retval = LoadPlugin<iC>(fullPathAndFileName, out bLoaded);
这是执行加载的函数:
public static T LoadPlugin<T>(string fullPathAndFileName, out bool loaded)
{
loaded = false;
T retval = default(T);
Assembly assembly = Assembly.LoadFile(fullPathAndFileName);
if (assembly != null)
{
Type pluginType = typeof(T);
// this is where I am getting the ReflectionTypeLoadException
Type[] types = assembly.GetTypes();
// Method 'TimeTrial' in type 'SI.SI_Engine'
// from assembly 'SI, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null'
// does not have an implementation.
//
foreach (Type type in types)
{
if (type.IsInterface || type.IsAbstract)
{
continue;
}
else
{
if (type.GetInterface(pluginType.FullName) != null)
{
retval = (T)Activator.CreateInstance(type);
loaded = true;
break;
}
}
}
}
return retval;
}
变化
我通过添加一个从旧接口派生的新接口来更改 P.DLL,并在 P 类中实现该函数:
public interface iP
{
string Version { get; }
}
public interface iP4 : iP
{
bool TimeTrial();
}
public class P : iP4
{
public P()
{
Version = "4.0";
}
#region iP Implementation
public string Version { get; private set; }
#endregion
#region iP4 Implementation
public bool TimeTrial()
{
return Version == "4.0";
}
#endregion
}
我也更改了 C.DLL 以使用派生自新接口:
public interface iC : iP4
{
// no interface changes here
}
随着 P 和 C 的变化:
SI(接口 iSI)源自 C(接口 iC),它源自 P(接口 iP 4)
SI (iSI) : C (iC) : P (iP4)
我进行了更改,重新编译了 P.DLL 和 C.DLL 以及我的应用程序。现在,当我运行应用程序时,我尝试加载使用OLD iP接口构建的 SI.DLL 实例,但出现异常。
我的问题是如何动态加载从以前的界面构建的程序集?