【问题标题】:Wrap a Linq query in a try/catch block using a method declaration使用方法声明将 Linq 查询包装在 try/catch 块中
【发布时间】:2012-11-07 22:16:39
【问题描述】:

这就是我想做的事情。

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

var a = Item.CatchLog().FirstOrDefault(x=>x.Property=="value");

var a = Item.CatchLog().Any(x=>x.Property=="value");

基本上,我希望 CatchLog() 基本上将查询的执行包装在 try catch 中,然后 Debug.WriteLine() Exception 然后 throw 它。

关于如何实现这样的东西有什么想法吗?

【问题讨论】:

    标签: c# .net linq extension-methods


    【解决方案1】:

    你需要重写你的陈述,像这样:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 2021-06-16
      • 2020-09-18
      • 1970-01-01
      • 2014-06-23
      • 2015-08-26
      • 2010-09-26
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多