System.ArgumentException Assembly.LoadModule(string,byte[]) 中的无效文件名

System.ArgumentException Invalid file name in Assembly.LoadModule(string,byte[])

在学习反射的过程中,遇到了.net模块

我明白这意味着我可以将单个 class 编译为 .net 模块(如果我错了请纠正我)然后使用 Assembly.LoadModule(string,byte[]) 加载这个已编译的 .net 模块.

我写了一个 class 看起来像这样的:

using System;
using System.Text;

public class Mycs {
    public static string GiveString(){
        return "Hello World !";
    }
}

并使用以下代码使用开关“/target:module”对其进行编译:

CodeDomProvider CDP = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters CP = new CompilerParameters();
CP.GenerateExecutable = false;
CP.CompilerOptions = "/target:module";
CP.OutputAssembly = FilePathText.Text.Replace(Strings.Right(FilePathText.Text, 3), ".netmodule");
string source = File.ReadAllText(FilePathText.Text);
CompilerResults RS = CDP.CompileAssemblyFromSource(CP, source);

然后我检索了结果文件字节:

byte[] b = File.ReadAllBytes(FilePathText.Text);

最后我尝试将模块加载到当前执行的程序集:

Module[] Modules = Assembly.GetExecutingAssembly().GetModules();
Module[] moduless = Assembly.GetExecutingAssembly().GetLoadedModules();
Module A = Assembly.GetExecutingAssembly().LoadModule(Modules[0].Name, b);

我是否通过了 Modules[0].Namemoduless[0].Name 都会导致此异常:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll Additional information: Invalid file name

为什么我会收到此无效文件名错误?

您不能将动态创建的模块加载到现有的程序集中,程序集一旦编译就是不可变的。

我最好的猜测是您需要使用 AssemblyBuilder.DefineDynamicModule() 在其中创建 类。在这种情况下,您创建的类型将自动加载。或将您的 类 编译为程序集,而不是模块,并使用 Assembly.LoadFile 方法动态加载这些程序集。