本文介绍了字典与委托或交换机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个解析器调用一些依赖于一定的价值功能。

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)
{
    case 0:
        func0();
        break;
    case 1:
        func1();
        break;
}

或代表和这样的字典:

delegate void some_delegate();
Dictionary<int, some_delegate> some_dictionary = new Dictionary<int, some_delegate>();
some_dictionary[0] = func0;
some_dictionary[1] = func1;

some_dictionary[some_value].Invoke();



是这两种方法等价的这是首选?

Are these two methods equivalent and which is preferred?

推荐答案

在准入方面,他们是相同的:都只是检查是否是特定的值都有相应的结果。但是,如果您尝试访问一个不存在的密钥字典将抛出一个超出范围的异常。

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.

的选择应主要放在重用性。如果你只需要作这个分支逻辑在一个点上,然后用一个开关的情况下可能使比存储变量更有意义。如果您需要多次访问它在不同的点,然后用字典来保存自己从刚刚重新粘贴switch语句反复。

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.

这篇关于字典与委托或交换机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:57