对不使用IF语句的命令列表执行命令C# [英] Perform Command For List of commands without using IF Statement C#
问题描述
我有一个 TcpListener
在 NetworkStream
上执行命令示例。 复制,移动,删除...
I have a TcpListener
Listening on a NetworkStream
to perform a command examples. "Copy, Move, Delete, ...."
switch(command)
{
case "copy":
// do copy
break;
case "delete":
// do delete
break;
case "move":
// do move
break;
.......................................
}
我已经使用 switch- case
code> if 语句,但是当涉及维护或添加新命令时,特别是当命令列表超出 100个命令时,它变得非常困难和乏味,是有办法有效地做到这一点,我试图搜索 Google ,但我似乎无法正确得到它的术语
任何帮助:) Yaser
i have implemented it using switch - case
and if
statement but when it comes to maintenance or adding a new command, specially when the commands list goes beyond 100 commands it becomes very hard and tedious, so is there a way to do this efficiently, i have tried searching on Google but i can't seem to get the jargon of it correctly
Any help :) Yaser
推荐答案
一个选项是定义字典< 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.
这篇关于对不使用IF语句的命令列表执行命令C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!