2011-03-04 73 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(); 
}