Reusing switch statement logic

What is the best way to reuse switch logic. I have this switch statement that continues to appear in my code. Instead, copy it, I would like to make a function that calls other delegates and passes these delegates as parameters.

Or is there a better way?

Function 1:

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

Function 2:

switch (test)
    {
        case "x":
            DoSomethingXxxx();
            break;
        case "y":
            DoSomethingYyyy();
            break;
        case "z":
            DoSomethingZyyy();
            break;
    }
+3
source share
3 answers

You could also have a dictionary (or Func instead of Action) or something like that (given that your functions have a similar signature). Then instead of using a switch, you could have something like:

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]();
    }
}

.

, switch.

+9

, .

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();
}
+4

As I try to understand your question, I can move on to the following:

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

Hope this helps.

Tiger

0
source

Source: https://habr.com/ru/post/1712589/


All Articles