使用 Roslyn CSharpScript 执行的调试脚本代码

Debug script code that is being executed with Roslyn CSharpScript

我使用 Roslyn 脚本引擎(在 Microsoft.CodeAnalysis.CSharp.Scripting nuget 包中为 运行 一些 C# 代码创建了这个测试控制台应用程序。

     string code = "int test = 123;\r\nConsole.WriteLine(\"hello, world!\");";
     var options = ScriptOptions.Default.WithImports("System");
     var script = CSharpScript.Create(code, options);
     await script.RunAsync();

这可行,但现在我还想要以某种方式调试正在执行的脚本的选项。有办法吗?

通过将代码写入临时文件并添加指向该文件的调试信息找到了一种方法。然后我可以进入 RunAsync 调用,visual studio 将加载临时文件,显示执行指针,并让我检查变量。

using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.IO;
using System.Text;

namespace RoslynScriptingTest
{
   class Program
   {
      static async Task Main(string[] args)
      {
         string code = "int test = 123;\r\nConsole.WriteLine(\"hello, world!\");";
         string tmpFile = Path.GetTempFileName();
         var encoding = Encoding.UTF8;
         File.WriteAllText(tmpFile, code, encoding);
         try
         {
            var options = ScriptOptions.Default
               .WithImports("System")
               .WithEmitDebugInformation(true)
               .WithFilePath(tmpFile)
               .WithFileEncoding(encoding);
            var script = CSharpScript.Create(code, options);
            await script.RunAsync();   
         }
         finally
         {
            File.Delete(tmpFile);
         }
         Console.ReadKey();
      }
   }
}

只有在 visual studio 调试器设置中启用“仅我的代码”时,调试才有效。

在我的实际用例中,我实际上是从 XML 文件加载代码,所以如果我可以指向该原始文件并以某种方式映射行号会更好。但这已经是一个好的开始。