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