开发者

C# External Array of Functions

Okay so it's about my project yet again. I have client and server. They communicate between each other and packets have following structure [OP CODE] [LENGTH] [DATA]

Now on server-side I wanna load function code for each OPcode from external .cs file.

So when compiled it will look like this

- OPCODES
-- OPCODE1.cs
开发者_StackOverflow社区-- OPCODE2.cs
-- OPCODE3.cs
-- OPCODE4.cs
OPCODES.cfg (has list of all op codes and location for function code)
MyProgram.exe

How would I do something like this?


You can create a Dictionary (assuming that the opcode is an integer

        Dictionary<int, Action> actions = new Dictionary<int, Action>();
        actions[7] = () => Console.WriteLine("hello World");

to execute opcode "7" you can do

        actions[7]();

if you want it more robust:

        Action action;
        if (actions.TryGetValue(7, out action))
            action();
        // else illegal opcode

If you want to load the actions Dictionary from a file it is a bit more complicated You can call the static method ConsoleApplicationTest.Program.MyMethod() via a Dictionary like this

namespace ConsoleApplicationTest
{
public class Program
{
    public static void MyMethod()
    {
        Console.WriteLine("MyMethod called");
    }
 } 
 }

The Dictonary can look like this

        Dictionary<int, MethodInfo> dynamicActions = new Dictionary<int, MethodInfo>();

        dynamicActions[7] = Assembly.GetExecutingAssembly().GetType("ConsoleApplicationTest.Program").GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Static);

and the method will be called like this

        MethodInfo method;
        if (dynamicActions.TryGetValue(7, out method))
            method.Invoke(null, new object[0]);


You can use case switch to signal that some packet received.

switch(packet.OpCode)
{
   case 1:
   OnHelloPacket();
   break;
   case 2:
   OnInfoPaket();
   break;
   //etc
}


It looks like you're looking for something much more dynamic than a simple enum or dictionary of actions. You mention in your question that "OPCODES.cfg (has list of all op codes and location for function code)". Does this imply that the opcode functions will not necessarily be compiled with the main server application?

If that's the case you'll likely be looking at some kind of plugin architecture, so you can add and remove opcode functions whenever you like. I'd recommend MEF as a good starting point.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜