gpt4 book ai didi

compiler-errors - OutKind.Console应用程序错误(Roslyn编译器)

转载 作者:行者123 更新时间:2023-12-02 10:56:27 25 4
gpt4 key购买 nike

I compiling with roslyn some Diagnostics Error showing My code is below:


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 Coming this line:--> var compileResult = compilation.Emit(stream); Err is: The name 'Console' doesn't exist in current context.(Diagnostics Err) how to solve this err

最佳答案

Console类型位于System.Console.dll
typeof(控制台)。装配体。位置-> 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"))
});

关于compiler-errors - OutKind.Console应用程序错误(Roslyn编译器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62414935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com