首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >c# dotNetCore -动态编译代码错误

c# dotNetCore -动态编译代码错误
EN

Stack Overflow用户
提问于 2020-07-01 08:42:16
回答 1查看 49关注 0票数 0

3.0

  • Microsoft.CodeAnalysis.CSharp 3.5.0
  1. .Net Core

代码语言:javascript
运行
复制
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

StringBuilder code = new StringBuilder();
code.AppendLine("namespace DotNetCoreTest");
code.AppendLine("{");
code.AppendLine("    public class TestCode");
code.AppendLine("    {");
code.AppendLine("        public int test(int a)");
code.AppendLine("        {");
code.AppendLine("            a++;");
code.AppendLine("            return a;");
code.AppendLine("        }");
code.AppendLine("    }");
code.AppendLine("}");

string sysFile = typeof(Enumerable).Assembly.Location;
string sysDir = Directory.GetParent(sysFile).FullName;

List<MetadataReference> references = new List<MetadataReference>();
references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.dll")));
references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.Xml.dll")));

string assemblyName = "DotNetCoreTest";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code.ToString());
CSharpCompilation compilation = CSharpCompilation.Create(assemblyName);
compilation.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
compilation.AddReferences(references);
compilation.AddSyntaxTrees(tree);

string targetPath = "D:\\test.dll";
EmitResult compilationResult = compilation.Emit(targetPath);

string err = "";
if (!compilationResult.Success)
{
    foreach (Diagnostic item in compilationResult.Diagnostics)
    {
        err += "\r\nid: " + item.Id + "\r\nerror: " + item.GetMessage() + "\r\nlocation: " + item.Location.GetLineSpan().ToString();
    }
}

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

我重复了多次测试,并出现了相同的错误消息。我的密码有什么问题吗?有谁可以帮我?谢谢

EN

回答 1

Stack Overflow用户

发布于 2021-01-12 01:24:35

谢谢大家。这个问题已经解决,下一次分享解决方案,但您必须添加依赖“Microsoft CodeAnalysis CSharp”。

代码语言:javascript
运行
复制
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;
    }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62672954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档