2011-03-04 26 views
0

我想用字典對象和提供的命令行參數做一些'動態'的操作。命令行參數是布爾值,然後我可以調用其中任何一個爲真的方法。所以...字典對象和錯誤的設計中的重複鍵值

public class CommandLineArguments 
{ 
    public bool AddSection1 { get; set; } 
    public bool AddSection2 { get; set; } 
    public bool Addsection3 { get; set; }   
} 

class RunSomeActions 
{ 
    private Dictionary<bool, Action> methodList = new Dictionary<bool, Action>(); 

    public RunSomeActions() 
    { 
     // create the switches as if from a command line 
     CommandLineArguments parameters = new CommandLineArguments(); 
     parameters.AddSection1 = true; 
     parameters.AddSection2 = false; 
     parameters.Addsection3 = true; 

     // setup the methods for the switches 
     methodList.Add(parameters.AddSection1, this.Section1); 
     methodList.Add(parameters.AddSection2, this.Section2); 
     methodList.Add(parameters.Addsection3, this.Section3); 

     foreach (var entry in methodList) 
     { 
      // if the switch is on 
      // call the method 
      if (entry.Key) 
       methodList[entry.Key](); 
     } 


    } 

    private void Section1() 
    { 
     // add specific entries into a file 
    } 

    private void Section2() 
    { 
     // perform analysis on a file 
    } 

    private void Section3() 
    { 
     // delete everything and start again 
    } 

} 

如果你只有真值和假值的兩個值,那麼這個工作很好,所以它實際上並不是很好。我喜歡這種方法,不需要手動解析參數,然後構建一個Action列表。有沒有辦法挽救這種設計?

回答

3

由於您實際上沒有使用字典進行查找,而僅僅用於存儲和迭代,而不是使用Dictionary<K,V>,因此您可以使用List<KeyValuePair<K,V>>

從代碼的角度的主要區別將被改變。新增到:

methodList.Add(new KeyValuePair<bool, Action>(parameters.AddSection1, this.Section1)); 

然後,當你使用,切換到:

foreach (var entry in methodList) 
{ 
    // if the switch is on 
    // call the method 
    if (entry.Key) 
     entry.Value(); // Execute "value" directly 
} 

話雖這麼說,你可以把這個可能會更進一步,並直接存儲List<Action>。只有在條件爲真的列表中添加動作,然後全部執行。

0

我建議創建一個結構。

struct MethodListItem 
{ 
    bool IsActive; 
    Action Action; 
} 

然後聲明methodList如(驚奇)一個List<MethodListItem>,並添加這樣的:

methodList.Add(new MethodListItem { IsActive = parameters.AddSection1, Action = this.Section1}); 
methodList.Add(new MethodListItem { IsActive = parameters.AddSection2, Action = this.Section2}); 
methodList.Add(new MethodListItem { IsActive = parameters.Addsection3, Action = this.Section3}); 

循環體便成爲稍微更可讀:

foreach (var entry in methodList) 
{ 
    // if the switch is on 
    // call the method 
    if (entry.IsActive) entry.Action(); 
}