c# 怎么把动态编译的结果存入流中
时间: 2024-10-10 11:07:23 浏览: 43
在 C# 中,如果你想将动态编译后的代码存储到流(Stream)中,通常可以使用 `System.CodeDom` 和 `System.Reflection.Emit` 模块。以下是一个简化的步骤:
1. 首先,创建一个 `CodeCompileUnit` 对象,用于编译代码:
```csharp
using System.CodeDom;
using Microsoft.CSharp;
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
string sourceCode = "your_code_here"; // 动态编写的代码字符串
CodeCompileUnit unit = new CodeCompileUnit();
unit.Namespaces.Add(new CodeNamespace("YourNamespace"));
unit.Types.Add(new CodeTypeDeclaration("YourClass")
{
Members = { new CodeMethodDefinition("YourMethod", MethodAttributes.Public) {
Body = new CodeMethodBody(sourceCode),
} }
});
```
2. 使用 `provider.CompileAssemblyFromCompileUnit` 方法编译代码并生成一个 `AssemblyBuilder`:
```csharp
CodeCompiler compiler = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.dll" }, "", "", true, OutputKind.DynamicallyLinkedLibrary);
parameters.GenerateExecutable = false; // 设置为目标库
parameters.GenerateInMemory = true; // 表示编译结果会保存在内存中
byte[] assemblyBytes = compiler.CompileAssemblyFromCompileUnit(unit, parameters);
```
3. 将编译后的字节数组(assemblyBytes)赋值给流:
```csharp
MemoryStream memoryStream = new MemoryStream(assemblyBytes);
```
现在,`memoryStream` 包含了动态编译的结果。你可以根据需要进一步操作这个流。
阅读全文
相关推荐


















