vendredi 17 janvier 2020

Storing object instance method with given attribute to be called later

As the title says, using reflection I get methods of the type that have a given attribute. I then want to store that method of that instance of the object so I can call it at a later time. I'm not sure how to store that method with that instance in a dictionary that holds Action. The message is the key use in the dictionary. All the methods that have this attribute will be required to take 1 argument of dynamic type.

static Dictionary<string, Action<dynamic>> networkHooks = new Dictionary<string, Action<dynamic>>();

private static void RegisterNetworkMethods(Type type, INetworkEnabled obj)
{
    // get the methods of this type that have the NetworkMethodAttribute
    var methods = (from m in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
                       where m.GetCustomAttributes(false).OfType<NetworkMethodAttribute>().Count() > 0
                       select m).ToList();

    foreach(var method in methods)
    {
        // get the NetworkMethodAttribute Message variable that was assigned
        var message = method.GetCustomAttribute<NetworkMethodAttribute>().Message;

        // todo: store this instance method in an Action somehow so it can be called later
        // networkHooks.Add(message, ???);
    }
}




Aucun commentaire:

Enregistrer un commentaire