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.
}
这篇关于我将如何使用反射来调用具有某个自定义属性的所有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我将如何使用反射来调用具有某个自定义属性的所有方法?


- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01