如何使用反射来调用具有特定自定义属性的所有方法?
我有一堂有很多方法的课程。
其中一些方法由自定义属性标记。
我想立即调用所有这些方法。
我将如何使用反射来查找该类中包含此属性的所有方法的列表?
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 would I go about using reflection to find a list of all the methods in that class that contains this attribute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
获取方法列表后,您可以使用 GetCustomAttributes 方法循环查询自定义属性。您可能需要更改 BindingFlags 以适合您的情况。
Once you get the list of methods, you would cycle query for the custom attributes using the GetCustomAttributes method. You may need to change the BindingFlags to suit your situation.
首先,您可以调用 typeof(MyClass).GetMethods() 来获取该类型上定义的所有方法的数组,然后循环遍历它返回的每个方法并调用 methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), true) 获取指定类型的自定义属性数组。如果数组长度为零,则您的属性不在该方法上。如果它非零,则您的属性位于该方法上,您可以使用 MethodInfo.Invoke() 来调用它。
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.