How to figure out dynamically all methods with custom attribute

一世执手 提交于 2019-12-06 11:50:35

The simplest approach is to use MethodInfo.IsDefined - quite possibly with LINQ as well:

var testMethods = from assembly in assemblies
                  from type in assembly.GetTypes()
                  from method in type.GetMethods()
                  where method.IsDefined(typeof(TestMethodAttribute))
                  select method;

foreach (var method in testMethods)
{
    Console.WriteLine(method);
}

(I'd do all the sorting with LINQ as well. Obviously you can tune the GetMethods call etc to only return instance methods, for example.)

It's not entirely clear to me why your current approach doesn't work or why it does work when you've created instances - but without a short but complete example demonstrating the problem, it would be hard to diagnose it further. I'd definitely start with the code above :)

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