jeudi 13 avril 2017

C# - Reflection and method properties

I have an attribute called NetworkEventAttribute which includes an enum in it's properties so I can identify it.

[AttributeUsage(AttributeTargets.Class)]
public class NetworkEventAttribute : Attribute
{
    public Messages Message { get; private set; }

    public NetworkEventAttribute(Messages message)
    {
        this.Message = message;
    }
}

I have several classes which inherit from my NetworkEvent abstract class that I tag using this attribute and each class includes a different enum value, for example:

[NetworkEvent(Messages.SomeMessage)]
public class SomeEvent : NetworkEvent
{
    public override void Handle(Client client)
}

public abstract class NetworkEvent
{
    public Rider Rider { get; set; }
    public Room Room { get; set; }

    public abstract void Handle(Client client, InPacket inPacket);
}

Now. I want to call Handle on a class based on the given enum. So I know I can get all the methods of a certain attribute like so:

 public static IEnumerable<Doublet<TAttribute, MethodInfo>> FindMethodsByAttribute<TAttribute>()
         where TAttribute : Attribute
    {
        return
            from a in AppDomain.CurrentDomain.GetAssemblies()
            from t in a.GetTypes()
            let attribute = t.GetCustomAttribute(typeof(TAttribute), false) as TAttribute
            where attribute != null
            select new Doublet<TAttribute, MethodInfo>(attribute, t.GetMethod("Handle"));
    }

However, I also want to set the Rider and Room properties before calling the method.

How can I do this?





Aucun commentaire:

Enregistrer un commentaire