C# 使用方法声明在try/catch块中包装Linq查询

C# 使用方法声明在try/catch块中包装Linq查询,c#,.net,linq,extension-methods,C#,.net,Linq,Extension Methods,这就是我希望能够做到的 var a = Item.CatchLog().Where(x=>x.Property=="value").Take(10); 或 或 本质上,我希望CatchLog()基本上将查询的执行包装在一个try-catch中,然后Debug.WriteLine()异常,然后抛出它 关于如何实现类似的内容,您有什么想法吗?您需要重写您的语句,如下所示: var a = Item.CatchLog(c => c.Where(x => x.Property=="v

这就是我希望能够做到的

var a = Item.CatchLog().Where(x=>x.Property=="value").Take(10);

本质上,我希望
CatchLog()
基本上将查询的执行包装在一个try-catch中,然后
Debug.WriteLine()
异常,然后
抛出它


关于如何实现类似的内容,您有什么想法吗?

您需要重写您的语句,如下所示:

var a = Item.CatchLog(c => c.Where(x => x.Property=="value").Take(10));
如果你允许的话,你可以这样写:

public static U CatchLog<T,U>(this IEnumerable<T> collection, Func<IEnumerable<T>,U> method)
{
    try
    {
        return method(collection);
    }
    catch(Exception e)
    {
         Debug.WriteLine(e.Message);
         throw;
    }
}
publicstaticu-CatchLog(此IEnumerable集合,Func方法)
{
尝试
{
退货方式(收款);
}
捕获(例外e)
{
Debug.WriteLine(e.Message);
投掷;
}
}
var a = Item.CatchLog(c => c.Where(x => x.Property=="value").Take(10));
public static U CatchLog<T,U>(this IEnumerable<T> collection, Func<IEnumerable<T>,U> method)
{
    try
    {
        return method(collection);
    }
    catch(Exception e)
    {
         Debug.WriteLine(e.Message);
         throw;
    }
}