gpt4 book ai didi

c# - 调试 .NET 动态方法

转载 作者:太空狗 更新时间:2023-10-29 23:28:08 25 4
gpt4 key购买 nike

我们在我们的系统中非常广泛地使用 LINQ。特别是 LINQ-to-objects。因此,在某些地方,我们最终会在内存中从一些巨大的表达式中构建 LINQ 查询。当表达式中存在一些错误时,问题就来了。所以我们得到 NullReferenceException 并且堆栈跟踪让我们无处可去(到 [Lightweight Function])。异常在 LINQ 生成的动态方法中抛出。

有什么简单的方法可以调试这种动态方法吗?还是我必须牺牲自己来学习 WinDBG? :-)

最佳答案

如果您要构建自己的表达式并编译它们,或者使用 AsQueryable,那么可以; LINQ 生成的方法调试起来非常痛苦。

您可以通过使用实际 方法的小片段来减轻一些痛苦——至少一些有用的东西会显示在堆栈跟踪中...

另一个考虑因素是:与其拥有一个庞大的表达式,不如将事物以菊花链的形式多一点,您可能会(从堆栈跟踪中)更清楚它在哪里失败。缺点是性能 - Where(foo).Where(bar) 是两个委托(delegate)调用,而 Where(foo && bar) 可以是一个。

一个选项可能是交换扩展方法的调试版本;不幸的是,这有点不方便,因为IQueryable<T>Queryable都在同一个命名空间中……不过这行得通……

先输出:

>Where: x => ((x % 2) = 0)
<Where: x => ((x % 2) = 0)
>Count
'WindowsFormsApplication2.vshost.exe' (Managed): Loaded 'Anonymously Hosted DynamicMethods Assembly'
<Count

代码:

using System;
using System.Diagnostics;
using System.Linq.Expressions;

namespace Demo
{
using DebugLinq;
static class Program
{
static void Main()
{
var data = System.Linq.Queryable.AsQueryable(new[] { 1, 2, 3, 4, 5 });
data.Where(x => x % 2 == 0).Count();
}
}
}
namespace DebugLinq
{
public static class DebugQueryable
{
public static int Count<T>(this System.Linq.IQueryable<T> source)
{
return Wrap(() => System.Linq.Queryable.Count(source), "Count");
}

public static System.Linq.IQueryable<T> Where<T>(this System.Linq.IQueryable<T> source, Expression<Func<T, bool>> predicate)
{
return Wrap(() => System.Linq.Queryable.Where(source, predicate), "Where: " + predicate);
}
static TResult Wrap<TResult>(Func<TResult> func, string caption)
{
Debug.WriteLine(">" + caption);
try
{
TResult result = func();
Debug.WriteLine("<" + caption);
return result;
}
catch
{
Debug.WriteLine("!" + caption);
throw;
}
}
}
}

关于c# - 调试 .NET 动态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/246112/

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