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

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

问题描述

我有一大堆的方法的类。

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天全站免登陆