Find methods that have custom attribute using reflection

后端 未结 3 782
不知归路
不知归路 2020-12-02 16:40

I have a custom attribute:

public class MenuItemAttribute : Attribute
{
}

and a class with a few methods:

public class Hell         


        
3条回答
  •  有刺的猬
    2020-12-02 17:07

    Your code is completely wrong.
    You are looping through every type that has the attribute, which will not find any types.

    You need to loop through every method on every type and check whether it has your attribute.

    For example:

    var methods = assembly.GetTypes()
                          .SelectMany(t => t.GetMethods())
                          .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)
                          .ToArray();
    

提交回复
热议问题