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

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

问题描述

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