gpt4 book ai didi

c# - 如何在已编译的表达式树中调试或设置 break 语句?

转载 作者:可可西里 更新时间:2023-11-01 08:27:36 29 4
gpt4 key购买 nike

当外部库包含 LINQ 提供程序时,它会在执行动态表达式树时抛出异常,我该如何在抛出该表达式时中断?

例如,我使用第三方 LINQ2CRM 提供商,它允许我调用 Max<TSource, TResult>() IQueryable的方法| , 但当它抛出一个 InvalidCastException ,当抛出异常时,我无法当场中断,因此很难查看堆栈跟踪,因为当调试器在我的代码中中断它时,它已经展开。我已经为提到的异常设置了“break on throw”。我的调试设置是:

enter image description here


澄清我想要打破的确切位置。我不想在 LINQ 表达式中中断,而是想在执行表达式树时中断,或者换句话说,在执行 IQueryable 时中断。扩展方法Max()调用 LINQ 提供程序提供的覆盖。堆栈跟踪的顶部看起来像这样,这是我想进入内部(或单步执行,或其他)的地方:

at XrmLinq.QueryProviderBase.Execute[T](Expression expression)
at System.Linq.Queryable.Max[TSource,TResult](IQueryable`1 source, Expression`1 selector)

最佳答案

我可能不理解这个问题,但与其实际中断(这似乎不可能),不如在表达式树中放置一个 try-catch 并记录异常是否足够?

static void Main(string[] args)
{
var logExceptionMethod = typeof (Program).GetMethod("LogException", BindingFlags.Static | BindingFlags.NonPublic);
var createFileMethod = typeof (System.IO.File).GetMethod("Create", new[] {typeof(string)});

// Parameter for the catch block
var exception = Expression.Parameter(typeof(Exception));

var expression =
Expression.TryCatch(
Expression.Block(typeof(void),
// Try to create an invalid file
Expression.Call(createFileMethod, Expression.Constant("abcd/\\"))),

// Log the exception from the catch
Expression.Catch(exception, Expression.Call(logExceptionMethod, exception)));

Expression.Lambda<Action>(expression).Compile()();
}

static void LogException(Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
}

控制台输出:

The filename, directory name, or volume label syntax is incorrect.

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.File.Create(String path)
at lambda_method(Closure )

关于c# - 如何在已编译的表达式树中调试或设置 break 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11012731/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com