【问题标题】:reusing switch statement logic重用 switch 语句逻辑
【发布时间】:2009-07-14 17:32:05
【问题描述】:

重用开关逻辑的最佳方法是什么。我有这个 switch 语句,它一直出现在我的代码中。而不是复制粘贴它,我想创建一个调用其他委托并将这些委托作为参数传递的函数。

或者有没有更好的方法?

功能1:

switch (test)
        {
            case "x":
                DoSomethingX();
                break;
            case "y":
                DoSomethingY();
                break;
            case "z":
                DoSomethingZ();
                break;
        }

功能2:

switch (test)
    {
        case "x":
            DoSomethingXxxx();
            break;
        case "y":
            DoSomethingYyyy();
            break;
        case "z":
            DoSomethingZyyy();
            break;
    }

【问题讨论】:

  • 您需要提供更多详细信息以便我们提供帮助。开关的哪些部分是不变的?只有案件本身,还是行动?你打开的变量怎么样,是一样的还是不同的?
  • 这听起来像是他在说案件是不变的,但行动会改变......但是,是的,我们需要更多细节。
  • 案件保持不变,行动改变

标签: c# switch-statement


【解决方案1】:

您还可以有一个字典(或 Func 而不是 Action)或类似的东西(考虑到您的函数具有类似的签名)。然后你可以不用开关,你可以有类似的东西:

public class MyClass
{
    Dictionary<string, Action> myDictionary;

    public MyClass()
    {
        BuildMyDictionary();
    }

    private Dictionary<int, Action<int, int>> BuildMyDictionary()
    {
        myDictionary.Add("x", DoSomethingX);
        myDictionary.Add("y", DoSomethingY);
        myDictionary.Add("z", DoSomethingZ);
        myDictionary.Add("w", DoSomethingW);
    }


    public void DoStuff()
    {
        string whatever = "x"; //Get it from wherever
        //instead of switch
        myDictionary[t]();
    }
}

我用一个类似的例子回答了一个类似的问题here

另外,请尝试在 switch 语句中使用枚举而不是字符串。

【讨论】:

    【解决方案2】:

    看看你是否可以使用接口和接口的不同实现来重构它。

    public interface Test {
        void DoSomething();
    }
    
    public class TestX : Test {
        void DoSomething() {
        }
    }
    
    public class TestY : Test {
        void DoSomething() {
        }
    }
    
    public class TestZ : Test {
        void DoSomething() {
        }
    }
    
    
    void func(Test test) {
        test.DoSomething();
    }
    

    【讨论】:

    • 对不起@Svish,我相信你下次会打败我。它以前发生过。 :)
    【解决方案3】:

    当我试图理解你的问题时,我可能会去以下:

    public enum Test{
        X, Y, Z
    }
    
    /**
    * test function call 
    * @a_Test - enumeration class for Test
    */
    public void test(Test a_Test){
     switch(a_Test){
       case X:
           x();
           break;
       case Y:
           y();
           break;
       case Z:
           z();
           break;
     }//switch
    }//test
    

    希望对你有帮助。

    老虎

    【讨论】:

      猜你喜欢
      • 2013-02-25
      • 2013-11-25
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多