![](/img/trans.png)
[英]ASP.NET vNext - MissingMethodException: Method not found: Microsoft.CodeAnalysis.Diagnostic> EmitResult.get_Diagnostics()'
[英]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.