c# - 如何使用 Microsoft.CodeAnalysis.Diagnostic 获取错误行

标签 c# diagnostics

希望您度过愉快的一天。 我有这段代码用于在运行时评估代码:

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);
                }
            }

当我收到错误时,例如它只会显示以下内容:错误 CS1520:方法必须有返回类型

如何获得类似 Error on line 2 CS1520: Method Must have a return type 的输出?

我已经尝试过diagnostic.Location,但我认为它返回装配线位置,这是我不需要的。有什么帮助吗?

最佳答案

可能有人仍在试图弄清楚。在 .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);
        }

关于c# - 如何使用 Microsoft.CodeAnalysis.Diagnostic 获取错误行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67818314/

相关文章:

IIS:在哪里可以找到 IIS 日志?

c# - 你能有 2 个 url 指向 asp :Menu control? 中的同一页面吗

c# - 如何让 StructureMap 返回请求类型的特定实例

c# - WndProc 将 lParam 挂接到 xy 线?

css - <button> 标签有什么缺点?

windows - 诊断监视器跟踪监听器

c# - .NET 4.7.1 项目无法使用 .NET Core 2.0 库

c# - GetTable 不适用于 Azure SQL 表(Xamarin Forms)

.net - 是否可以在 .NET 的调用堆栈中获取每个帧的参数值

hadoop - hive 无法创建 map /减少工作