【问题标题】:Passing command line arguments to roslyn compiler将命令行参数传递给 roslyn 编译器
【发布时间】:2020-10-25 22:01:13
【问题描述】:

我想知道在编译和执行代码时是否有办法将命令行参数传递给 roslyn。

我当前用于生成编译器和执行源代码的代码如下所示:

CSharpCompilation compilation = CSharpCompilation.Create(Path.GetFileName(assemblyPath))
  .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
  .AddReferences(references)
  .AddSyntaxTrees(syntaxTree);

using (var memStream = new MemoryStream())
{
  var result = compilation.Emit(memStream);
  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());
    }
  }
  else
  {
    memStream.Seek(0, SeekOrigin.Begin);
    Assembly assembly = Assembly.Load(memStream.ToArray());
    var test = assembly;
  }
}

我们的目标是拥有类似这样的某种源代码:

using System;

class Program
{
  static string StringToUppercase(string str)
  {
    return str.ToUppercase();
  }

  static void Main(string[] args)
  {
    string str = Console.ReadLine();
    string result = StringToUppercase(str);
    Console.WriteLine(result);
  }

}

我可以在其中传递命令行参数并获取 Console.WriteLine() 的结果。处理这个问题的最佳方法是什么?当前代码确实构建并将编译和分析源代码。

代码将编写在 .NET core 3.1 mvc Web 应用程序中。

【问题讨论】:

    标签: c# .net-core roslyn roslyn-code-analysis


    【解决方案1】:

    我猜你想将参数传递给已编译的应用程序而不是 roslyn :)
    执行编译后的代码,使用Console.SetOut(TextWriter)获取其输出(例如:sof link):

    Assembly assembly = Assembly.Load(memStream.ToArray());
    // Console.SetOut to a writer
    var test = assembly.EntryPoint.Invoke(null, new object[] { "arg1", "arg2" });
    // And restore it
    

    或为它启动一个新进程:

    memStream.CopyTo(File.OpenWrite("temp.exe"))
    // Copied from MSDN
    // https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput
    using (Process process = new Process())
    {
        process.StartInfo.FileName = "temp.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.Start();
    
        // Synchronously read the standard output of the spawned process.
        StreamReader reader = process.StandardOutput;
        string output = reader.ReadToEnd();
    
        // Write the redirected output to this application's window.
        Console.WriteLine(output);
    
        process.WaitForExit();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 2015-06-09
      • 2017-10-22
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多