samedi 18 novembre 2017

Using reflection to find classes and invoke properly

I have an abstract class called Action which accepts a byte array and represents actions done by the client. I have several actions that are implemented from this class and they contain properties, like so:

[Action(ActionCode.Login)]
public class LoginAction : Action
{
    public string Username { get; private set; }
    public string Password { get; private set; }

    public LoginAction(byte[] data)
        : base(data)
    {
        this.Username = this.ReadMapleString();
        this.Password = this.ReadMapleString();
    }
}

I want to be able to defind a method using the actions like so:

public static void Login(LoginAction action)

So when I receive data from the client I can handle the actions based on the code received. However, I'm not sure how to use reflection to find the method that's associated with the action. I mean, I can find LoginAction using the code under, but I can't find the method that's using LoginAction as a parameter, which is the method I want to invoke.

I want to achieve something like:

public void OnRecieveData(ActionCode code, byte[] data)
{
    // Using the ActionCode, call the specified action handler method.
    // Login(new LoginAction(data));
}

I already know how to find classes that use the ActionCodeAttribute, but I'm not sure how to invoke it:

static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly) {
    foreach(Type type in assembly.GetTypes()) {
        if (type.GetCustomAttributes(typeof(HelpAttribute), true).Length > 0) {
            yield return type;
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire