比如Action<T>或者Fun<T>来优化大量条件判断的switch case 语句 

解决方案 »

  1.   

    private Dictionary<bool, Action> dic;   //确认时执行的代码   
        private void Confirm()  
        {  
            lit.Text = "确认";  
        }  
      
        //取消时执行的代码   
        private void Cancel()  
        {  
            lit.Text = "取消";  
        }  //赋值
                dic = new Dictionary<bool, Action>();  
      
                dic.Add(true, Confirm);  
                dic.Add(false, Cancel);  //调用
             dic[result]();  引自 confirm 确认框的一个实际应用(续) http://blog.csdn.net/sandy945/article/details/5716632
      

  2.   

    (1)设计模式中的策略模式:
    void foo(int type)
    {
        dosth1();
        switch (type)
        {
            case 0:
                Console.WriteLine("0");
                break;
            case 1:
                Console.WriteLine("1");
                break;
        }
        dosth2();
    }
    foo(0);
    foo(1);
    转化为:
    void foo(Action action)
    {
        dosth1();
        action();
        dosth2();
    }
    foo(() => Console.WriteLine("0"));
    foo(() => Console.WriteLine("1"));
      

  3.   

    还有个办法是设计模式的模板模式:
    void foo(int type)
    {
        dosth1();
        switch (type)
        {
            case 0:
                Console.WriteLine("0");
                break;
            case 1:
                Console.WriteLine("1");
                break;
        }
        dosth2();
    }
    foo(0);
    foo(1);
    转化为
    void foo(MethodBase mb)
    {
        dosth1();
        mb.Do();
        dosth2();
    }class MethodBase
    {
        public virtual void Do() { }
    }
    class Method0 : MethodBase
    {
        public override void Do() { Console.WriteLine("0"); }
    }
    class Method1 : MethodBase
    {
        public override void Do() { Console.WriteLine("1"); }
    }foo(new Method0());
    foo(new Method1());顺便说一下,WinForms在将消息处理分支转化为Control对象成员的时候,就是使用的模板模式。
    你可以重写 WndProc() 来改变消息处理。
      

  4.   

     一楼,dic[result](); 调用具体是怎样的呢,希望举个例子