gpt4 book ai didi

Roslyn:从元模型创建程序集

转载 作者:行者123 更新时间:2023-12-04 13:50:14 27 4
gpt4 key购买 nike

在我投入大量时间学习 roslyn 编译器服务之前,我想问一下 roslyn 是否可以实现以下场景。是否可以编译程序集而无需将任何内容写入磁盘并执行它?我基于元模型生成完整的解决方案,我想采用它并编译并执行它。罗斯林有可能吗?

最佳答案

这是一个稍微轻一点的版本:

// Some standard references most projects use
var references = new List<MetadataReference>
{
MetadataReference.CreateAssemblyReference("mscorlib"),
MetadataReference.CreateAssemblyReference("System"),
MetadataReference.CreateAssemblyReference("System.Linq"),
new MetadataFileReference(this.GetType().Assembly.Location)
};

// The MyClassInAString is where your code goes
var syntaxTree = SyntaxTree.ParseText(MyClassInAString);

// Use Roslyn to compile the code into a DLL
var compiledCode = Compilation.Create(
"MyAssemblyName",
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: syntaxTree,
references: references;
);

// Now read the code into a memory stream. You can then load types out of the assembly with reflection
Assembly assembly;
using (var stream = new MemoryStream())
{
EmitResult compileResult = compiledCode.Emit(stream);
if (!compileResult.Success)
{
throw new InvalidOperationException("The assembly could not be built, there are {0} diagnostic messages.".FormatWith(compileResult.Diagnostics.Count()));
}
assembly = Assembly.Load(stream.GetBuffer());
}

关于Roslyn:从元模型创建程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17679343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com