开发者

Storing methods in a dictionary for custom Tcp or Udp server. Is it a good idea? C#

开发者 https://www.devze.com 2023-03-17 06:28 出处:网络
I am considering storing methods inside of a dictionary (using a friendly user-readable string as a key) so that a message like \"echo, hello world\" can be sent to the server and the Server will know

I am considering storing methods inside of a dictionary (using a friendly user-readable string as a key) so that a message like "echo, hello world" can be sent to the server and the Server will know to call: echo(string message) and pass in "hello world".

Pseudo code:

public delegate void NetCommand(object param);开发者_如何学编程

void MyNetCommand(object param)
{
  string s = param as string;

  Console.WriteLine(s);
}

Dictionary<string, NetCommand> commands = new Dictionary<string, NetCommand>();

static void Main(string[] args)
{
  commands.Add("echo", MyNetCommand);
} 

void OnReceiveSomeImaginaryMessageAfterItsBeenProcessed(string friendly, object param)
{
  commands[friendly]();
}

My question is: is this a good idea? Are there any drawbacks to doing this? Or, is this just the "wrong" way to do something that already has a desirable solution?


I don't see why it's not a good Idea, and the fact that you storing them in memory will mean that you get a proformance boost aswell.


It looks cool, just use

if (commands.HasKey(friendly)) 

... before doing it...

you also lack param as in:

commands[friendly](param);


I personaly think it's elegant enough solution. The single think I will personally change is: instead puting into the Value of dictionary a delefate, put a class object. In this case yuo can easily support in the future increasing complexity of your code.

public abstract class MyAbstractNetCommand {   

     public abstract void ExecuteCommand();
} 

public class ConcreteCommand : MyAbstractNetCommand {

    /*Here additional ConcreteCommand specific methods and state members*/

    public override ExecuteCommand() {
       // concrete iplementation
    }
}


You're performance will be O(log(n)), however switch/case over string will have the same O(log(N)) performance, so you do not do anything bad. Anyway command routing should not be a bottleneck.

0

精彩评论

暂无评论...
验证码 换一张
取 消