Dictionary with delegate or switch?

后端 未结 6 1414
一生所求
一生所求 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<int, Action>
    {
      {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.

    0 讨论(0)
  • 2021-02-07 01:47

    Both do the same (well you should check if the key appears in the dictonary).

    It is just a matter of readability. What looks the best for your and more important, what do people reading your code would prefer.

    (I think the dictionary)

    0 讨论(0)
  • 2021-02-07 01:50

    If the typical programmer on your team is anything like the ones I often deal with, you should go for the simplest option i.e. the switch. The delegates seem to me like a 'clever' solution that is not needed.

    0 讨论(0)
  • 2021-02-07 01:57

    If you need to switch on strings in a resource file, say for globalization purposes, then you'll need to use the dictionary/delegate approach.

    0 讨论(0)
  • 2021-02-07 02:00

    I like the dictionary approach because it gives you the ability to possibly swap out your lambda expressions as the need arises. This is a great trick for a programmer to keep in their tool bag for cases involving programs using complex decision trees. It would be very unwieldy to modify your switch case blocks at run time and the best answer would end up involving lambdas anyway.

    I once had a situation where I needed to create a switch statement dynamically. This method provided a lot more readable solution.

    0 讨论(0)
  • 2021-02-07 02:03

    In terms of access, they're identical: both just check if that specific value has a corresponding result. However, a Dictionary will throw an out-of-bounds exception if you try to access a non-existent key.

    The choice should primarily be on re-usability. If you only need to make this branching logic at one point, then using a switch-case is probably makes more sense than storing a variable. If you need to access it repeatedly in separate points, then use the Dictionary to save yourself from just re-pasting the switch-statement repeatedly.

    0 讨论(0)
提交回复
热议问题