mercredi 14 septembre 2016

One Generic Method To Handle Mutliple Delegate Types

I'm working on a project that allows the Client to call remote functions on the Server for its specific instance. Basically, when the client connects it will get its own instance of a shared class, the Client will then call the server with the name of the method return type, and parameters + their expected types.

The way I'm going about it is creating a Prototypes class, and inside it creating Delegates to represent the Method prototypes that are inside the Server's shared class.

  • Sub Question: What is the best method to go about this? I'm using Delegates but I'm not a fan of double declarations for what's effectively one prototype. An Interface is about what I want, but I can find a good way to create an instance of it because I'm not sure what the Prototype class will contain.

The way I will handle all this is when the Client connects to the Server, the Client will traverse the Prototypes class and get all Fields, it will then attempt to link all of the Fields inside to one generic method to handle any function that gets called, that function will then get it's declared return type & parameter info etc. and then send it off to the server.

My first thought was to use

params object[] param

However Delegate.CreateDelegate errors out at runtime if I say feed it:

public delegate string TestDelegate(string s1, string s2, string[] s3);

public TestDelegate Test;

However, if I create multiple overloads of the Method that all the delegates are linking back to it works fine ex:

    public T handleFunc<T>(object param)
    {
        Console.WriteLine(param as string);
        return default(T);
    }

    public T handleFunc<T>(object param, object param2)
    {
        Console.WriteLine(param as string);
        return default(T);
    }

    public T handleFunc<T>(object param, object param2, object param3)
    {
        Console.WriteLine((param3 as string[])[0]);
        return default(T);
    } 

Here's my current code to link the delegates to the handleFunc method:

    private void ValidatePrototypes()
    {
        var fields = typeof(Prototypes).GetFields();
        foreach (FieldInfo field in fields)
        {
            MethodInfo thisfield = field.FieldType.GetMethods()[0];

            ParameterInfo[] pi = thisfield.GetParameters();

            var handle = typeof(Client).GetMethod("handleFunc", Array.ConvertAll(pi, s => s.ParameterType));

            var lambda = handle.MakeGenericMethod(thisfield.ReturnType);

            Delegate del = Delegate.CreateDelegate(field.FieldType, this, lambda);

            field.SetValue(Functions, del);
        }
        Console.WriteLine(Functions.Test("", "", new[] { "Hello" }));
    }

I effectively need one method for any possible delegate (or whatever the best variant is) to link to and be able to handle the data from there.

I appreciate any responses.





Aucun commentaire:

Enregistrer un commentaire