2015-12-21 42 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 
    } 
} 
相關問題