c# - 当 CompilerParameters.GenerateInMemory == true 时,在运行时编译类失败

标签 c# reflection

我正在运行时编译动态程序集。它需要引用另一个 dll。一切正常,只要我在 CompilerParameters 中设置 OutputAssembly。但是一旦我设置 GenerateInMemory = true;它失败了:

var compilerParameters = new CompilerParameters();
if( compileInMemory )
    compilerParameters.GenerateInMemory = true;
else
    compilerParameters.OutputAssembly = "<my_dynamic_dll_path>";
compilerParameters.ReferencedAssemblies.Add( "<other_dll_path>" );
var compilerResults = new CSharpCodeProvider().CompileAssemblyFromDom( compilerParameters, codeCompileUnit );

// Here: compilerResults.Errors.HasErrors == false

foreach( var type in compilerResults.CompiledAssembly.GetTypes() )
{
     // Exception:
     // Unable to load one or more of the requested types.
     // Retrieve the LoaderExceptions property for more information.
}

LoaderExceptions 告诉我找不到“other_dll”。为什么只要我不在内存中编译它就可以工作,我必须做什么才能让它在内存中工作?

最佳答案

使用 GenerateInMemory 时没有加载上下文,程序集由 Assembly.Load(Byte[]) 重载加载。一种解决方法是临时 Hook AppDomain.AssemblyResolve 事件,以便您可以自己加载“other_dll”。

关于c# - 当 CompilerParameters.GenerateInMemory == true 时,在运行时编译类失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/591806/

相关文章:

c# - 如何使用 "if statement"wpf 禁用日期选择器

c# - View 模型的单独项目到 "enforce"MVVM : How do I open dialogs?

c# - C++控制台程序的前端

api - 通过反射获取方法参数值

c# - 在 VS2010 中运行测试项目的 Microsoft.Web.Administration 出现 ReflectionTypeLoadException

c# - Dijkstra 的算法团队项目未运行,因为我将其命名为 Dijkstra(项目名称)?

c# - 检查 JValue 是否为空

C# 反射 : How to get the properties of the derived class from the base class

java - Java 枚举反射

java - 自定义类加载/覆盖 Android 原生类