Dictionary with delegate or switch?

后端 未结 6 1415
一生所求
一生所求 2021-02-07 01:21

I am writing a parser which calls some functions dependent on some value.

I can implement this logic with simple switch like this:

switch(some_val)            


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 01:41

    I strongly prefer the dictionary choice, because with an initializer, it can be a lot more compact and readable:

    var actions = new Dictionary
    {
      {1, () => Console.WriteLine("One!")},
      {2, () => Console.WriteLine("Two!")}
    }
    

    Also, you have some more flexibility; you can add conditions and actions programatically, which is often handy, depending on what you're doing.

提交回复
热议问题