我将如何使用反射来调用具有某个自定义属性的所有方法? [英] How would I use reflection to call all the methods that has a certain custom attribute?

查看:14
本文介绍了我将如何使用反射来调用具有某个自定义属性的所有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一堆方法的类.

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.

}

这篇关于我将如何使用反射来调用具有某个自定义属性的所有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆