【问题标题】:OutKind.ConsoleApplication Err(Roslyn Compiler)OutKind.ConsoleApplication Err(Roslyn 编译器)
【发布时间】:2020-06-16 18:06:52
【问题描述】:

我用 roslyn 编译了一些诊断错误,显示我的代码如下:

using System;
using System.Reflection;
using System.Runtime.Loader;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System.IO;
using Microsoft.CodeAnalysis;

namespace RoslynTest
{
    public class Test
    {
        public static void Main(string[] args)
        {
             const string code =@"using System;
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(""Hello, World!"");
        }
    }
}";

        var tree = SyntaxFactory.ParseSyntaxTree(code);
            var compilation = CSharpCompilation.Create("HelloWorldCompiled.exe", options: new CSharpCompilationOptions(OutputKind.ConsoleApplication),
                syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) });
            using (var stream = new MemoryStream())
            {
                var compileResult = compilation.Emit(stream);
                var assembly = Assembly.Load(stream.GetBuffer());
                assembly.EntryPoint.Invoke(null, BindingFlags.NonPublic | BindingFlags.Static, null, new object[] { null }, null);
            }
        }
    }
}

Err 来到这一行:--> var compileResult = compilation.Emit(stream); 错误是:当前上下文中不存在名称“控制台”。(诊断错误) 如何解决这个错误

【问题讨论】:

标签: compiler-errors roslyn roslyn-code-analysis roslyn-project-system


【解决方案1】:

Console 类型位于System.Console.dll

typeof(Console).Assembly.Location -> C:\Program Files\dotnet\shared\Microsoft.NETCore.App\...\System.Console.dll

这可以通过使用正确的参考来解决:

var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
var tree = SyntaxFactory.ParseSyntaxTree(code);
var compilation = CSharpCompilation.Create("HelloWorldCompiled", 
    options: new CSharpCompilationOptions(OutputKind.ConsoleApplication),
    syntaxTrees: new[] { tree },
    references: new[]
    {
        MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
        MetadataReference.CreateFromFile(Path.Combine(runtimeDir, "System.Console.dll")),
        MetadataReference.CreateFromFile(Path.Combine(runtimeDir, "System.Runtime.dll"))
    });

【讨论】:

  • 嗨@karthick19892089。这回答了你的问题了吗? :)
  • 为了帮助有类似问题的其他用户,您可以接受该解决方案。这也将节省其他人的时间,因为它会将问题标记为已回答。
猜你喜欢
  • 1970-01-01
  • 2016-06-19
  • 2018-12-06
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
相关资源
最近更新 更多