C# - 反射和方法属性

时间:2017-04-13 09:51:49

标签: c# reflection

我有一个名为NetworkEventAttribute的属性,其中包含一个枚举属性,因此我可以识别它。

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

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

我有几个继承自我的NetworkEvent抽象类的类,我使用此属性进行标记,每个类包含不同的枚举值,例如:

[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);
}

现在。我想基于给定的枚举在类上调用Handle。所以我知道我可以得到某种属性的所有方法:

 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"));
    }

但是,我还想在调用方法之前设置RiderRoom属性

我该怎么做?

编辑:我让反射方法返回IEnumerable<Doublet<TAttribute, Type>>然后我让我的get方法返回类似的类型:

public NetworkEvent GetHandler(Messages message, Client client, InPacket inPacket)
    {
        if (!_handlers.ContainsKey(message))
            return null;

        NetworkEvent handler = (NetworkEvent)Activator.CreateInstance(_handlers[message]);
        handler.Rider = client.Rider;
        handler.Room = client.Rider?.Room;

        return handler;
    }

然后我打电话给:

var handler = Server.Instance.GetHandler(inPacket.Message, this, inPacket);
                if (handler == null)
                    Console.WriteLine("Unhandled packet of type '{0}'.", inPacket.Message.ToString());
                else
                {
                    try
                    {
                        handler.GetType().GetMethod("Handle").Invoke(handler.GetType(), new object[2] { this, inPacket });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error while handling packet from {0}: \n{1}", this.Host, ex.ToString());
                    }
                }

这是正确的方法吗?

0 个答案:

没有答案