Dictionary with delegate or switch?

后端 未结 6 1416
一生所求
一生所求 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题