簡體   English   中英

使用反射獲取具有特定屬性值的方法

[英]Using reflection to get methods with certain attribute value

我有這個代表:

 public delegate void PacketHandler(Client client, Packet packet);

我有這個屬性:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class PacketHandlerAttribute : Attribute
{
    public ServerType Server { get; private set; }
    public int Code { get; private set; }

    public PacketHandlerAttribute(ServerType server, int code)
    {
        this.Server = server;
        this.Code = code;
    }
}

我想根據給定的ServerType值創建一個方法來返回IEnumerable<Tuple<PacketHandlerAttribute, PacketHandler>> 因此,如果我使用ServerType.Server調用此方法,它將返回所有包含Server1作為其屬性的方法。

到目前為止,我做到了:

public static IEnumerable<Doublet<PacketHandlerAttribute, PacketHandler>> GetPacketHandlers(ServerType server)
    {
        foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
        {
            foreach (MethodInfo method in type.GetMethods())
            {
                PacketHandlerAttribute attribute = (PacketHandlerAttribute)method.GetCustomAttribute(typeof(PacketHandlerAttribute));

                if (attribute != null)
                {
                    if (attribute.Server == server)
                    {
                        yield return new Doublet<PacketHandlerAttribute, PacketHandler>(attribute, (PacketHandler)Delegate.CreateDelegate(typeof(PacketHandler), method));
                    }
                }
            }
        }
    }

我想問一下這是否是正確的方法,而LINQ如何縮短它呢?

我認為這會有所幫助。

 var methods = from type in assembly.GetTypes()
                      from method in type.GetMethods()
                      let attribute = method.GetCustomAttributes(typeof(PacketHandlerAttribute), false).Cast<PacketHandlerAttribute>().FirstOrDefault()
                      where attribute?.Code == 1
                      select new { method, attribute };

你的方法

public IEnumerable<(PacketHandlerAttribute attribute, PacketHandler handler)> GetPacketHandlers(ServerType server)
        {
            var assembly = Assembly.GetEntryAssembly();

            return from type in assembly.GetTypes()
                          from method in type.GetMethods()
                          let attribute = method.GetCustomAttributes(typeof(PacketHandlerAttribute), false).Cast<PacketHandlerAttribute>().FirstOrDefault()
                          where attribute?.Server == server
                          select (attribute, (PacketHandler)method.CreateDelegate(typeof(PacketHandler)));
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM