且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对不使用IF语句的命令列表执行命令C#

更新时间:2023-11-11 20:20:16

一个选项是定义字典< string,action> 在类级别上,它将保存命令的名称和一个动作委托给需要执行的实际方法。然后在您的主要方法中,您不需要使用开关,只需获取 action 从字典中委托使用字典的 TryGetValue 方法,如果返回true,只需调用动作委托。

One option is to define a Dictionary<string,action> on the class level that will hold the name of the command and an action delegate to the actual method that needs to be performed. Then in your main method you don't need to use a switch, simply get the action delegate from the dictionary using the dictionary's TryGetValue Method and if it returns true simply invoke the action delegate.