我想用字典对象和提供的命令行参数做一些'动态'的操作。命令行参数是布尔值,然后我可以调用其中任何一个为真的方法。所以...字典对象和错误的设计中的重复键值
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列表。有没有办法挽救这种设计?