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必须是const,除了枚举,没什么写死了的
并且枚举switch的代码可以自动生成
但是比switch要慢,比if也慢。但是这种模式比较适合分支扩展和运行时注入分支逻辑。
属于消息的一种。从效率上来说与switch和if没法比,这一点可以自行测试。