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

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

问题描述

基于 MSDN示例的问题。

假设我们在独立的桌面应用程序中有一些C#类与HelpAttribute。是否有可能枚举所有类与这样的属性?以这种方式识别类有意义吗?自定义属性将用于列出可能的菜单选项,选择项将带来此类的屏幕实例。

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