2010-11-24 80 views
0

我在C#中发现了一些关于异常过滤的question。我想为它写一些模拟。我不知道它对人有什么帮助,我也没有使用VB过滤。当然,这不是优化和生产准备,但工作和做必须做的事情(我怎么理解这个问题)。所以工作草图:带过滤的C#异常监视器

using System; 


namespace ExceptionFiltering 
{ 
    class ExceptionMonitor 
    { 
     Action m_action = null; 

     public ExceptionMonitor(Action action) 
     { 
      this.m_action = action; 
     } 

     public void TryWhere(Func<Exception, bool> filter) 
     { 
      try 
      { 
       this.m_action(); 
      } 
      catch (Exception ex) 
      { 
       if (filter(ex) == false) 
       { 
        throw; 
       } 
      } 
     } 

     public static void TryWhere(Action action, Func<Exception, bool> filter) 
     { 
      try 
      { 
       action(); 
      } 
      catch (Exception ex) 
      { 
       if (filter(ex) == false) 
       { 
        throw; 
       } 
      } 
     } 
    } 

    class Program 
    { 
     //Simple filter template1 
     static Func<Exception, bool> m_defaultExceptionFilter = ex => 
     { 
      if (ex.GetType() == typeof(System.Exception)) 
      { 
       return true; 
      } 

      return false; 
     }; 

     //Simple filter template2 
     static Func<Exception, bool> m_notImplementedExceptionFilter = ex => 
     { 
      if (ex.GetType() == typeof(System.NotImplementedException)) 
      { 
       return true; 
      } 

      return false; 
     }; 


     static void Main(string[] args) 
     { 
      //Create exception monitor 
      ExceptionMonitor exMonitor = new ExceptionMonitor(() => 
      { 
       //Body of try catch block 
       throw new Exception(); 
      }); 

      //Call try catch body 
      exMonitor.TryWhere(m_defaultExceptionFilter); 


      //Call try catch body using static method 
      ExceptionMonitor.TryWhere(() => 
      { 
       //Body of try catch block 
       throw new System.NotImplementedException(); 

      }, m_notImplementedExceptionFilter); 


      //Can be syntax like ExceptionMonitor.Try(action).Where(filter) 

      //Can be made with array of filters 
     } 
    } 
} 

待办事项:全局异常处理程序,支持多个过滤器等;

谢谢你的任何建议,更正和优化!

+2

什么是你的问题? – cdhowie 2010-11-24 16:43:14

+1

@cdhowie:我认为这个问题是'你的建议是什么?' – 2010-11-24 16:45:16

回答

2

对不起,我是C#的新手,所以我无法理解你的代码,但我仍然希望我的建议能够提供帮助。

if (somecondition) 
{ 
    return true; 
} 
else 
{ 
    return false; 
} 

可以简单:

return somecondition; 

而且你需要检查空调用之前Action

if (m_action!=null) m_action();