我正在使用 CSharpScript.EvaluatyAsync<T>
评估脚本方法并传递一些 C# 代码。
当出现解析问题时,我可以很容易地看到错误的行号,例如一个语法错误,但是当出现运行时异常时,我得到的只是一个 AggregateException
在这种情况下包装我的异常 ( NullReferenceException
),但不知道如何为我获取行号(在下面的示例中为 3)。
Console.WriteLine(CSharpScript.EvaluateAsync<int>(
@"string s = null;
// some comment at line 2
var upper = s.ToUpper(); // Null reference exception at line 3
// more code").Result);
编辑:
我一直在研究这个问题,发现脚本 API 创建了一个没有 pdb 信息的程序集 here line 127所以这将不可能知道异常发生在哪里。我说得对吗?
最佳答案
在 CSharpScript 的某些版本中,团队添加了一个解决方案:现在您可以将 ScriptOptions.Default.WithEmitDebugInformation(true)
添加到 EvaluateAsync
方法。
有关如何提取异常行号的信息,请参阅下面的测试用例:
[TestMethod]
public void LineNumberInStackTrace()
{
try
{
var result = CSharpScript.EvaluateAsync<int>(
@"string s = null;
// some comment at line 2
var upper = s.ToUpper(); // Null reference exception at line 3
// more code", ScriptOptions.Default.WithEmitDebugInformation(true)).Result;
}
catch (AggregateException e)
{
if (e.InnerException is NullReferenceException inner)
{
var startIndex = inner.StackTrace.IndexOf(":line ", StringComparison.Ordinal) + 6;
var lineNumberStr = inner.StackTrace.Substring(
startIndex, inner.StackTrace.IndexOf("\r", StringComparison.Ordinal) - startIndex);
var lineNumber = Int32.Parse(lineNumberStr);
Assert.AreEqual(3, lineNumber);
return;
}
}
Assert.Fail();
}
[TestMethod]
public void LineNumberNotInStackTrace()
{
try
{
var result = CSharpScript.EvaluateAsync<int>(
@"string s = null;
// some comment at line 2
var upper = s.ToUpper(); // Null reference exception at line 3
// more code").Result;
}
catch (AggregateException e)
{
if (e.InnerException is NullReferenceException inner)
{
var startIndex = inner.StackTrace.IndexOf(":line ", StringComparison.Ordinal);
Assert.AreEqual(-1, startIndex);
return;
}
}
Assert.Fail();
}
关于c# - CSharpScript.EvaluateAsync 中的异常行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37125385/