[英]How to compile in memory and get assembly using Microsoft.CodeAnalysis
Before I was using System.CodeDom.Compiler.在我使用 System.CodeDom.Compiler 之前。 It has options that allow compiling in memory and return assembly:
它具有允许在 memory 中编译并返回程序集的选项:
var compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
};
I am migrating to .net core and I am using Microsoft.CodeAnalysis to compile from the string.我正在迁移到 .net 核心,我正在使用 Microsoft.CodeAnalysis 从字符串进行编译。 But I couldn't find 'compile in memory' function on it.
但是我在上面找不到'compile in memory' function。 My goal is to validate the syntax issue of code.
我的目标是验证代码的语法问题。 Currently my code is:
目前我的代码是:
var sources = GenerateSourceFromDefaultValue(context, defaultValue, clrType, isEnum);
var parsedSyntaxTree = Parse(sources, "", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
var compilation = CSharpCompilation.Create("Test.dll", new SyntaxTree[] { parsedSyntaxTree }, options: DefaultCompilationOptions);
The following code worked on me以下代码对我有用
Assembly assembly = null;
using (var memoryStream = new MemoryStream())
{
var emitResult = compilation.Emit(memoryStream);
if (emitResult.Success)
{
memoryStream.Seek(0, SeekOrigin.Begin);
var assemblyLoadContext = AssemblyLoadContext.Default;
assembly = assemblyLoadContext.Assemblies.FirstOrDefault(a => a.GetName()?.Name == AssemblyName);
if (assembly == null)
{
assembly = assemblyLoadContext.LoadFromStream(memoryStream);
}
}
}
return assembly;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.