Find methods that have custom attribute using reflection

后端 未结 3 783
不知归路
不知归路 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();
    
    0 讨论(0)
  • 2020-12-02 17:15
    var classType = new ClassNAME();
    var methods = classType.GetType().GetMethods().Where(m=>m.GetCustomAttributes(typeof(MyAttribute), false).Length > 0)
    .ToArray();
    

    Now you have all methods with this attribute MyAttribute in class classNAME. You can invoke it anywhere.

    public class ClassNAME
    {
        [MyAttribute]
        public void Method1(){}
    
        [MyAttribute]
        public void Method2(){}
    
        public void Method3(){}
    }
    
    0 讨论(0)
  • 2020-12-02 17:26
    Dictionary<string, MethodInfo> methods = assembly
        .GetTypes()
        .SelectMany(x => x.GetMethods())
        .Where(y => y.GetCustomAttributes().OfType<MethodAttribute>().Any())
        .ToDictionary(z => z.Name);
    
    0 讨论(0)
提交回复
热议问题