簡體   English   中英

如何使用 Microsoft.CodeAnalysis.Diagnostic 獲取錯誤行

[英]How to get error line using Microsoft.CodeAnalysis.Diagnostic

祝你今天愉快。 我有這段代碼用於在運行時評估代碼:

SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText("Code goes here...");
string assemblyName = Path.GetRandomFileName();

            string corePath = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile("Newtonsoft.Json.dll"),
                MetadataReference.CreateFromFile(Path.Combine(corePath, "System.Net.dll")),
                MetadataReference.CreateFromFile(Path.Combine(corePath, "System.Text.RegularExpressions.dll"))
            };

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                        diagnostic.IsWarningAsError ||
                        diagnostic.Severity == DiagnosticSeverity.Error);

                    string errors = "";

                    foreach (Diagnostic diagnostic in failures)
                    {
                        errors += "<span style=\"text-align: center;\">Error <b>" + diagnostic.Id + "</b>: " + diagnostic.GetMessage() + "</span><br>";
                    }

                    return errors;
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());

                    Type type = assembly.GetType("NoteBoxCode.Program");
                    object obj = Activator.CreateInstance(type);
                    return type.InvokeMember("Main", BindingFlags.InvokeMethod, null, obj, null);
                }
            }

例如,當我收到錯誤時,它只會顯示: Error CS1520: Method must have a return type

我怎樣才能得到 output Error on line 2 CS1520: Method must have a return type

我已經嘗試過diagnostic.Location ,但我認為它返回了我不需要的裝配線位置。 有什么幫助嗎?

因此, CSharpCompilationOptions不能返回錯誤行,因為它是運行時錯誤。 我需要一個高級調試 class,分別調試和運行每一行代碼,這就是(我認為)visual studio 所做的。

您可以使用SyntaxTree.GetDiagnostics()來獲得語法錯誤的概述。 但是,這不會返回編譯錯誤,例如Console.WritLine而不是Console.WriteLine

可能有人仍在試圖弄清楚。 in.Net 6 我能夠讓它工作

for (int i = 0; i < CompilationResults.Diagnostics.Length; i++)
        {
            var d = CompilationResults.Diagnostics[i];

            var parts = d.ToString().Replace("(", "").Replace(")", "").Split(',');

            var err = new ScriptError();
            err.Line = parts[0];
            err.ErrorNumber = "";
            err.ErrorText = d.GetMessage();

            if (d.Severity == DiagnosticSeverity.Error)
                Results.Errors.Add(err);
            else
                Results.Warnings.Add(err);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM