我想用字典對象和提供的命令行參數做一些'動態'的操作。命令行參數是布爾值,然後我可以調用其中任何一個爲真的方法。所以...字典對象和錯誤的設計中的重複鍵值
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列表。有沒有辦法挽救這種設計?