如何在内存中编译并使用 Microsoft.CodeAnalysis 获取程序集

How to compile in memory and get assembly using Microsoft.CodeAnalysis

在我使用 System.CodeDom.Compiler 之前。它有允许在内存中编译和 return assembly:

的选项
var compilerParams = new CompilerParameters
        {
            GenerateInMemory = true,
            GenerateExecutable = false,
        };

我正在迁移到 .net 核心,我正在使用 Microsoft.CodeAnalysis 从字符串进行编译。但是我在上面找不到 'compile in memory' 函数。我的目标是验证代码的语法问题。目前我的代码是:

 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);

以下代码对我有效

 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;