我正在按照http://support.microsoft.com/kb/837908中的方法 3 在 C# 中动态加载程序集。但是,代码对我不起作用。在以下代码部分中,作者仅在缺失程序集的名称是应用程序引用的程序集之一时才加载缺失的程序集。
当我在调试下运行它时,该函数被调用,但缺少的程序集不在任何这些引用的程序集中,因此在我的情况下没有设置它。任何想法为什么会发生这种情况?我不确定该 DLL 是 C# 还是本机 C++。这可能是因为 C++ dll 无法以这种方式加载吗?那么,为什么会为缺少的 C++ 程序集调用此函数?任何解释表示赞赏。如果这不适用于从 C# 引用的 C++ 程序集,还有哪些替代方法?
private Assembly MyResolveEventHandler(object sender,ResolveEventArgs args)
{
//This handler is called only when the common language runtime tries to bind to the assembly and fails.
//Retrieve the list of referenced assemblies in an array of AssemblyName.
Assembly MyAssembly,objExecutingAssemblies;
string strTempAssmbPath="";
objExecutingAssemblies=Assembly.GetExecutingAssembly();
AssemblyName [] arrReferencedAssmbNames=objExecutingAssemblies.GetReferencedAssemblies();
//Loop through the array of referenced assembly names.
foreach(AssemblyName strAssmbName in arrReferencedAssmbNames)
{
//Check for the assembly names that have raised the "AssemblyResolve" event.
if(strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(","))==args.Name.Substring(0, args.Name.IndexOf(",")))
{
//Build the path of the assembly from where it has to be loaded.
strTempAssmbPath="C:\\Myassemblies\\"+args.Name.Substring(0,args.Name.IndexOf(","))+".dll";
break;
}
}
//Load the assembly from the specified path.
MyAssembly = Assembly.LoadFrom(strTempAssmbPath);
//Return the loaded assembly.
return MyAssembly;
}