希望您度过愉快的一天。 我有这段代码用于在运行时评估代码:
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/