How would I use reflection to call all the methods that has a certain custom attribute?

后端 未结 2 1283
耶瑟儿~
耶瑟儿~ 2020-12-17 02:08

I have a class with a bunch of methods.

some of these methods are marked by a custom attribute.

I would like to call all these methods at once.

How

2条回答
  •  一生所求
    2020-12-17 02:37

    First, you would call typeof(MyClass).GetMethods() to get an array of all the methods defined on that type, then you loop through each of the methods it returns and call methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), true) to get an array of custom attributes of the specified type. If the array is zero-length then your attribute is not on the method. If it's non-zero, then your attribute is on that method and you can use MethodInfo.Invoke() to call it.

提交回复
热议问题