简体   繁体   English

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

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

i hope you have a great day.祝你今天愉快。 I have this piece of code for evaluating code on runtime:我有这段代码用于在运行时评估代码:

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

And when i get an error, for example it just shows this: Error CS1520: Method must have a return type例如,当我收到错误时,它只会显示: Error CS1520: Method must have a return type

How can i get an output like Error on line 2 CS1520: Method must have a return type ?我怎样才能得到 output Error on line 2 CS1520: Method must have a return type

I have tried diagnostic.Location , but i think it returns assembly line location, which i do not need.我已经尝试过diagnostic.Location ,但我认为它返回了我不需要的装配线位置。 Any help?有什么帮助吗?

So, CSharpCompilationOptions cannot return an error line, as it is a runtime error.因此, CSharpCompilationOptions不能返回错误行,因为它是运行时错误。 I will need an advanced debugging class, to debug and run each line of code seperately, which is what ( i think ) visual studio does.我需要一个高级调试 class,分别调试和运行每一行代码,这就是(我认为)visual studio 所做的。

You can use SyntaxTree.GetDiagnostics() to get an overview of the syntax errors.您可以使用SyntaxTree.GetDiagnostics()来获得语法错误的概述。 however this does not return compilation errors, such as Console.WritLine instead of Console.WriteLine .但是,这不会返回编译错误,例如Console.WritLine而不是Console.WriteLine

May be some one is still trying to figure it out.可能有人仍在试图弄清楚。 in.Net 6 I was able to make it work 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.

相关问题 ASP.NET vNext - MissingMethodException:找不到方法:Microsoft.CodeAnalysis.Diagnostic> EmitResult.get_Diagnostics()' - ASP.NET vNext - MissingMethodException: Method not found: Microsoft.CodeAnalysis.Diagnostic> EmitResult.get_Diagnostics()' 如何在 memory 中编译并使用 Microsoft.CodeAnalysis 获取程序集 - How to compile in memory and get assembly using Microsoft.CodeAnalysis 使用 Microsoft.CodeAnalysis,如何获取 Type 类型的 Attribute 属性的值? - Using Microsoft.CodeAnalysis, how do I get the value of an Attribute property that is of type Type? 如何使用 Microsoft.CodeAnalysis(或类似)获取项目(.csproj)的目标框架? - How to get the Target Framework/s of a project (.csproj) using Microsoft.CodeAnalysis (or similar)? 如何为Microsoft.codeAnalysis.CSharp配置BindingRedirects - How to config BindingRedirects for Microsoft.codeAnalysis.CSharp 如何使用 Roslyn 获取范围内所有可见的局部变量名称(Microsoft CodeAnalysis) - How to get all visible local variable names within a scope with Roslyn (Microsoft CodeAnalysis) Microsoft.CodeAnalysis:使用Newtonsoft JObject编译动态代码时出错 - Microsoft.CodeAnalysis: Error compiling dynamic code with Newtonsoft JObject 使用Roslyn(Microsoft.CodeAnalysis)查询WebSite项目的信息 - Using Roslyn (Microsoft.CodeAnalysis) to query information of WebSite projects 如何将Microsoft.CodeAnalysis.ITypeSymbol与System.Type进行比较 - How to compare a Microsoft.CodeAnalysis.ITypeSymbol to a System.Type 在Roslyn(Microsoft CodeAnalysis)中,如何创建布尔文字? - In Roslyn (Microsoft CodeAnalysis) how do I create a boolean literal?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM