2014-12-03 46 views
0

我有两个事件处理程序具有完全相同的代码,但处理不同的事件除外。我怎样才能将这些结合起来使用相同的代码而不必重复自己?将两种方法重构为一个具有相同字段但名称不同的方法

static void SharePointEventHandler(object sender, SharePointEventArgs e) 
{ 
    switch (e.ExceptionType) 
    { 
     case SharePointEventArgs.ExceptionLevel.Debug: 
      CLog(LogType.Debug, e.Message); 
      break; 

     case SharePointEventArgs.ExceptionLevel.Info: 
      CLog(LogType.Info, e.Message); 
      break; 

     case SharePointEventArgs.ExceptionLevel.Error: 
      CLog(LogType.Error, e.Message, e.Exception); 
      break; 
    } 
} 

static void FTPEventHandler(object sender, FTPEventArgs e) 
{ 
    switch (e.ExceptionType) 
    { 
     case FTPEventArgs.ExceptionLevel.Debug: 
      CLog(LogType.Debug, e.Message); 
      break; 

     case FTPEventArgs.ExceptionLevel.Info: 
      CLog(LogType.Info, e.Message); 
      break; 

     case FTPEventArgs.ExceptionLevel.Error: 
      CLog(LogType.Error, e.Message, e.Exception); 
      break; 
    } 
} 
+1

那些自定义事件参数类型?你能改变事件签名吗? – BradleyDotNET 2014-12-03 01:00:42

+1

正如Bradley所问,'SharePointEventArgs'和'FTPEventArgs'之间有什么关系。有什么关系吗?这里最大的问题是方法体实际上是不相同的。每个使用看起来是'EventArgs'子类特有的'enum'。如果这两个值以某种方式共享(例如,'enum'被声明在'EventArgs'子类之外),会更容易。 – 2014-12-03 01:05:31

+1

没有两个eventArg类型之间的关系,直接的方法是使用共享逻辑创建第三个方法,并且两个现有方法都有一个调用它的单独一行。但这不是您要求的一种方法解决方案。 – hatchet 2014-12-03 01:10:38

回答

3

根据代码的当前状态,有多种方法可以重构此代码。我假设目前,这两个EventArgs子类根本就没有关系。恕我直言,最好的办法是改变这一点。具体而言,创建一个基类,无论是现有的子类的派生:

class ExceptionEventArgs : EventArgs 
{ 
    public enum ExceptionLevel 
    { 
     Debug, 
     Info, 
     Error 
    } 

    public ExceptionLevel ExceptionType { get; set; } 
    public string Message { get; set; } 
    public Exception Exception { get; set; } 
} 

class SharePointEventArgs : ExceptionEventArgs { ... } 
class FTPEventArgs : ExceptionEventArgs { ... } 

然后你可以使用相同的事件处理程序,这两个事件:

static void SharePointEventHandler(object sender, ExceptionEventArgs e) 
{ 
    switch (e.ExceptionType) 
    { 
     case ExceptionEventArgs.ExceptionLevel.Debug: 
      CLog(LogType.Debug, e.Message); 
      break; 

     case ExceptionEventArgs.ExceptionLevel.Info: 
      CLog(LogType.Info, e.Message); 
      break; 

     case ExceptionEventArgs.ExceptionLevel.Error: 
      CLog(LogType.Error, e.Message, e.Exception); 
      break; 
    } 
} 

这需要对方差支持的优势。 .NET委托类型。委托实例可以将任何方法作为目标,该方法接收为委托类型指定的确切类型的参数,或者可以从为委托类型指定的参数中指定的参数。

相关问题