如何枚举具有自定义类属性的所有类? [英] How enumerate all classes with custom class attribute?

查看:26
本文介绍了如何枚举具有自定义类属性的所有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题基于 MSDN 示例.

假设我们在独立桌面应用程序中有一些带有 HelpAttribute 的 C# 类.是否可以枚举具有此类属性的所有类?以这种方式识别类有意义吗?自定义属性将用于列出可能的菜单选项,选择项目将显示此类类的屏幕实例.类/项目的数量会缓慢增长,但我认为这样我们可以避免在其他地方枚举它们.

Let's say we have some C# classes with HelpAttribute in standalone desktop application. Is it possible to enumerate all classes with such attribute? Does it make sense to recognize classes this way? Custom attribute would be used to list possible menu options, selecting item will bring to screen instance of such class. Number of classes/items will grow slowly, but this way we can avoid enumerating them all elsewhere, I think.

推荐答案

是的,绝对的.使用反射:

Yes, absolutely. Using Reflection:

static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly) {
    foreach(Type type in assembly.GetTypes()) {
        if (type.GetCustomAttributes(typeof(HelpAttribute), true).Length > 0) {
            yield return type;
        }
    }
}

这篇关于如何枚举具有自定义类属性的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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