2015-12-21 44 views
1

我是C#(.NET 4.0)项目的新雇员,但我来自C/C++背景。我被指示要“普遍改进我们的产品”,并且遇到了一种长达1000行的方法,其中大部分是由单个开关语句组成,每个语句包含15个情况,每个约60行代码。有没有办法重构C#独有的switch语句?

这个演出之前,我会保持相同的通用格式,但提取的15个功能,然后制定了如何根据需要共享/指向局部变量/类的数据成员。不过,我现在可以访问各种神秘的新工具,我不能动摇这种感觉,即有一种“C#聪明”的方式去实现这一点。

有没有办法来重构在C#(4.0)这个switch语句可能不是在C++做什么?

编辑:以下是代码的消毒和摘要的形式:

private void DeviceRequest(List<OpRequest> currentOp, double adjTime) { 
    //local variables 

    while (/*condition*/) 
    { 
     //Some setup 
     //Some initialization 

     try 
     { 
      switch (OperationType) 
      { 
       case Setup: 
        //Message header setup through 'if-else' statements 
        //Message sending 
        //Many nested 'if' checks, a few less 'else's 
        break; 

       case Initiate: 
        //Message header setup through 'if-else' statements 
        //Message sending 
        //Many nested 'if' checks, a few less 'else's 
        break; 

       case Acquire: 
        //Message header setup through 'if-else' statements 
        //Message sending 
        //Many nested 'if' checks, a few less 'else's 
        break; 

       case Measure: 
        //Message header setup through 'if-else' statements 
        //Message sending 
        //Many nested 'if' checks, a few less 'else's 
        break; 

       case Reset: 
        //Message header setup through 'if-else' statements 
        //Message sending 
        //Many nested 'if' checks, a few less 'else's 
        break; 

       //12 more cases, all fairly similar. 
      } 
     } 

     catch (RunTimeError err) 
     { 
      //A few lines of code 
     } 

     finally 
     { 
      //Objective measure of time passage 
     } 
    } 
} 
+4

告诉我们更多关于开关的情况。您对案件之间的重复有何一般看法? – ChaosPandion

+3

每当你看到一个'switch'语句时,你就知道错过了一个子类的机会。不幸的是,这个问题过于宽泛,无法提供具体的重构。 – dasblinkenlight

+0

@dasblinkenlight我不是在寻找一个特定的重构,我很好奇,如果有任何功能/关键字特殊的C#,用于重构的情况下,我已经描述过。 – HireThisMarine

回答

1

enumswitch通常可以通过一个动作Dictionary代替。为了做好准备,每个动作必须处理相同的输入。

如果您可以将代码重构为具有相同签名的15个方法的集合,则可以将它们放入Dictionary<OpRequest,DelegateType>,其中DelegateType是具有方法签名的委托。

例如,如果每15种方法有以下

private void SetupAction(double adjTime) { 
    ... 
} 
void InitiateAction(double adjTime) { 
    ... 
} 

签名,你可以建立在地方行动

private readonly IDictionary<OpRequest,Action<double>> OpActions = new Dictionary<OpRequest,Action<double>> { 
    {OperationType.Setup, SetupAction} 
, {OperationType.Initiate, InitiateAction} 
, ... // and so on 
}; 

有了这本字典的字典,你可以重写你的循环如下:

while (/*condition*/) { 
    //Some setup 
    //Some initialization 
    try { 
     Action<double> action; 
     if (OpActions.TryGetValue(opType, out action)) { 
      action(adjTime); 
     } else { 
      ... // Report an error: unknown OpRequest 
     } 
    } catch (RunTimeError err) { 
     ... //A few lines of code 
    } 
    finally { 
     ... //Objective measure of time passage 
    } 
} 
相关问题