如果您正在构建自己的表达式并编译它们,或者使用 AsQueryable,那么可以; LINQ 生成的方法调试起来非常痛苦。
您可以通过使用实际方法的小片段来节省一些痛苦 - 至少有用的东西会显示在堆栈跟踪中......
另一个考虑因素是:与其拥有一个巨大的表达式,不如通过菊花链更多的东西,你可能会(从堆栈跟踪)知道它失败的地方。缺点是性能 - Where(foo).Where(bar) 是两个委托调用,where-as 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;
}
}
}
}