OutKind.ConsoleApplication Err (компилятор Roslyn) - PullRequest
0 голосов
/ 16 июня 2020

Я компилирую с помощью 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 ); Ошибка: имя «Консоль» не существует в текущем контексте. (Ошибка диагностики) как решить эту ошибку

1 Ответ

0 голосов
/ 26 июня 2020

Тип 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"))
    });

...