do this without using an “if” | if(s == “value1”){…} else if(s == “value2”) { …}

前端 未结 18 2380
温柔的废话
温柔的废话 2021-01-30 09:36

According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also

18条回答
  •  忘掉有多难
    2021-01-30 10:10

    A little late to the party, but combining the C# dictionary answers from MRFerocius and cletus gives the following implementation of bmargulies's answer:

    private Dictionary data = new Dictionary {
        {"foo", () => Console.WriteLine("Some logic here")},
        {"bar", () => Console.WriteLine("something else here")},
        {"raboof", () => Console.WriteLine("of course I need more than just WriteLine")},
    }
    
    public static void main(String[] args) {
        data["foo"]();
    }
    
    • If the key doesn't exist in the dictionary, using it in the indexer will throw an exception.
    • Multiple actions can be composed:

      • There can be multiple calls to different methods, using multiline lambda syntax:

        {"foobar", () => { data["foo"](); data["bar"](); }

      • As Action is a delegate type, multiple methods can be attached to a single delegate instance and that delegate instance set as the value; they will be called sequentially when the delegate is invoked:

        public static void main(String[] args) { data["foobar"] = data["foo"] + data["bar"]; //This will invoke first data["foo"] then data["bar"] data["foobar"](); }

        For methods not referenced via the dictionary, this can also be done in the collection initializer:

        {"foobar", (Action)method1 + method2}

提交回复
热议问题