Find methods that have custom attribute using reflection

穿精又带淫゛_ 提交于 2019-11-27 12:17:56

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();
Dictionary<string, MethodInfo> methods = assembly
    .GetTypes()
    .SelectMany(x => x.GetMethods())
    .Where(y => y.GetCustomAttributes().OfType<MethodAttribute>().Any())
    .ToDictionary(z => z.Name);
var class = new 'ClassNAME'();
var methods = class.GetType().GetMethods().Where(m=>m.GetCustomAttributes(typeof(MyAttribute), false).Length > 0)
.ToArray();

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

public class 'ClassNAME': IDisposable
 {
     [MyAttribute]
     public string Method1(){}

     [MyAttribute]
     public string Method2(){}

     public string Method3(){}
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!