How would I use reflection to call all the methods that has a certain custom attribute?(我将如何使用反射来调用具有某个自定义属性的所有方法?)
问题描述
我有一个包含一堆方法的类.
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?
推荐答案
获得方法列表后,您将使用 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.
var methods = typeof( MyClass ).GetMethods( BindingFlags.Public );
foreach(var method in methods)
{
var attributes = method.GetCustomAttributes( typeof( MyAttribute ), true );
if (attributes != null && attributes.Length > 0)
//method has attribute.
}
这篇关于我将如何使用反射来调用具有某个自定义属性的所有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我将如何使用反射来调用具有某个自定义属性的所有方法?


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01