表达式树中的调试信息

问题描述 投票:0回答:0

有没有办法将调试信息插入 .NET 表达式树中,以便它显示在异常跟踪中(例如,源代码位置和自定义函数名称)。

例如,给定代码(定义了一个将两个参数相除的函数,并用第二个参数调用它

0
):

// Define the lambda expression
var x = Expression.Parameter(typeof(int), "x");
var y = Expression.Parameter(typeof(int), "y");
var op = Expression.Divide(x, y);
var debug = Expression.DebugInfo(
    Expression.SymbolDocument("test.txt"),
    1, 5, 4, 13);
var bl = Expression.Block(debug, op);
var lambdaExpr = Expression.Lambda<Func<int, int, int>>(
    bl,
    new[] { x, y });

// Compile the lambda expression to a delegate
var compiled = lambdaExpr.Compile();

// Create a function that invokes the compiled delegate with some arguments
Func<int, int, int> invokeDelegate = (xArg, yArg) => compiled(xArg, yArg);

// Invoke the function with some arguments
invokeDelegate(20, 0);

最终的堆栈跟踪是:

Unhandled exception. System.DivideByZeroException: Attempted to divide by zero.
   at lambda_method1(Closure , Int32 , Int32 )
   at ExpressionTreeExample.<>c__DisplayClass0_0.<Main>b__0(Int32 xArg, Int32 yArg) in .../workspace/test/Program.cs:line 23
   at ExpressionTreeExample.Main() in .../workspace/test/Program.cs:line 26

在这个例子中,有没有办法将调试信息添加到表达式中,以便在异常跟踪中显示“test.txt”(和其他提供的信息)?

注意:我对 .NET Core 感兴趣,而不是 Framework。谢谢!

c# .net-core compiler-construction expression-trees
© www.soinside.com 2019 - 2024. All rights reserved.