Sending a dynamic method based on the value of a variable

Long-term switch statuses are often not approved. The solution is to use polymorphism. However, what if the thing I include is not a type code? What I would like to do is replace the switch statement with something like this ...

public void HandleString(string s = "Hello")
{
 ...
}

public void HandleString(string s = "Goodbye")
{
 ...
}

...
HandleString("Hello"); // results in the first method being called.

This will replace the following ...

string s = "Hello";

switch(s)
{
   case "Hello":
   ...
   break;
   case "Goodbye":
   ...
   break;
   default;
   break;
}

Any ideas? Theoretically, I think that you can completely abandon the "if / switch" statements and simply call methods that are automatically bound based on the value of the expression.

+3
source share
2 answers

, . , Elegant Phillips.

:

fact (value : Int) : Int
    conditions value < 0
{
    { "Illegal input value\n" } astype Message
    return 0
}

fact (value = 0) : Int
{
    return 0
}

fact (value = 1) : Int
{
    return 1
}

fact (value : Int) : Int
{
    return value * fact(value - 1);
}
+1

, - , , :

Dictionary<string, Action<string>> actions =
    new Dictionary<string, Action<string>>()
    {
        { "Hello", HandleHello },
        { "Goodbye", HandleGoodbye }
    };

private static void HandleHello(string s) { ... }

private static void HandleGoodbye(string s) { ... }

...

actions[s](s);

, API .

+16

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


All Articles