日期:2014-05-18  浏览次数:21042 次

能不能用字典表+委托替代switch?
C# code

class Program
{
    delegate string Func();

    static void Main(string[] args)
    {
        var Dict = new System.Collections.Generic.Dictionary<string, Func>();

        Dict["Apple"] = new Func(Apple);
        Dict["Google"] = new Func(Google);
        Dict["IBM"] = new Func(IBM);

        string cmd;
        while ("exit" != (cmd = System.Console.ReadLine()))
        {
            if (Dict.ContainsKey(cmd))
                System.Console.WriteLine(Dict[cmd]());
        }
    }

    static string Apple() { return "Apple()"; }
    static string Google() { return "Google()"; }
    static string IBM() { return "IBM()"; }
}


数据量大的时候用这种字典表+委托的方式替代switch有没有什么不好的地方?

------解决方案--------------------
这种思路我觉得很好啊,效率比switch更快。switch相当于依次比较的,而字典表只需要比较一次(查一次hash表)更重要的是容易扩展。
------解决方案--------------------
貌似只有在枚举上才用switch
switch必须是const,除了枚举,没什么写死了的
并且枚举switch的代码可以自动生成
------解决方案--------------------
这样是可以的。
但是比switch要慢,比if也慢。但是这种模式比较适合分支扩展和运行时注入分支逻辑。
属于消息的一种。从效率上来说与switch和if没法比,这一点可以自行测试。
------解决方案--------------------
...感觉就是visitor