c#dotNetCore-动态编译代码时出错

时间:2020-07-01 08:42:16

标签: .net-core

  1. .Net Core 3.0
  2. Microsoft.CodeAnalysis.CSharp 3.5.0
myComboBox.DisplayMember = "FriendlyName";

id:CS8021 错误:找不到RuntimeMetadataVersion的值。找不到包含System.Object的程序集,也没有通过选项指定RuntimeMetadataVersion的值。 位置::(0,0)-(0,0) 编号:CS5001 错误:程序不包含适用于入口点的静态“ Main”方法 位置::( 0,0)-(0,0)

我重复了多次测试,并且出现相同的错误消息。我的代码有问题吗?谁能帮我?谢谢

1 个答案:

答案 0 :(得分:1)

谢谢大家。这个问题已经解决了,接下来分享解决方案, 但是你必须添加一个依赖 'Microsoft CodeAnalysis CSharp'

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public class CodeCompiler
{

    Assembly TranslateCode(string code, ref string err)
    {
        Assembly asse = null;

        Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
        List<MetadataReference> metadataReferences = new List<MetadataReference>();
        PortableExecutableReference portable = null;
        int len = asses.Length;
        int num = 0;
        Assembly item = null;
        while (num < len)
        {
            try
            {
                item = asses[num];
                if (string.IsNullOrEmpty(item.Location)) continue;
                portable = MetadataReference.CreateFromFile(item.Location);
                metadataReferences.Add(portable);
            }
            catch (Exception)
            {

                //throw;
            }
            finally
            {
                num++;
            }
        }
            
        var references1 = metadataReferences.ToArray(); 

        string assemblyName = Path.GetRandomFileName();

        SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
            
        CSharpCompilation compilation = CSharpCompilation.Create(
            assemblyName,
            syntaxTrees: new[] { syntaxTree },
            references: references1, 
            options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

        using (var ms = new MemoryStream())
        {
            EmitResult result = compilation.Emit(ms);

            if (!result.Success)
            {
                IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                    diagnostic.IsWarningAsError ||
                    diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    //Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    err += string.Format("{0}: {1}", diagnostic.Id, diagnostic.GetMessage())+"\r\n";
                }
            }
            else
            {
                // The assembly is loaded from memory when the compilation is successful
                ms.Seek(0, SeekOrigin.Begin);
                asse = Assembly.Load(ms.ToArray());
            }
        }

        return asse;
    }

}