Method Factory - case vs. reflection

后端 未结 4 447
北恋
北恋 2020-12-15 11:17

I came across some code the other day and I wondered if that was the best way to do it. We have a method that takes a string from some web form data a does something to an

4条回答
  •  感情败类
    2020-12-15 11:50

    You can fix @user287107's answer thusly:

    var Actions = new Dictionary>();
    Actions["DoX"] = DoX;
    Actions["DoY"] = DoY;
    Actions["DoZ"] = DoZ;
    

    This is in effect doing the discovery phase of @Lucero's answer explicitly, which may be useful if the names don't always match.

    Defining the set of actions in an enum would also be nice if possible - this would be a tiny bit faster as you wouldn't need to hash the strings. It would also enable you to write a unit test to make sure you've not missed any potential values.

提交回复
热议问题