识别具有某些属性的所有类型

时间:2010-04-10 10:15:39

标签: .net reflection custom-attributes

我有.Net反思的问题。这个概念对我来说是相当新的,我正在用一些测试用例来探索它,看看哪些有用,哪些无效。我正在构建一个示例,其中我通过扫描我的类型属性来动态填充一组菜单。

基本上,我想在我的主命名空间中找到声明'SomeAttribute'的所有类型(无论它是什么,它目前没有任何成员)。我所做的是:

    For Each itemtype As Type In Reflection.Assembly.GetExecutingAssembly().GetTypes
        If itemtype.IsDefined(Type.GetType("SomeAttribute"), False) Then
            'do something with the type
        End If
    Next

这会在启动时崩溃应用程序 - 它识别的第一个类型是MyApplication,这显然不是我想要的。是否有正确的方法来寻找所有“真正的”敏感的类型 - 即我已定义的类 - 在当前的汇编中?

2 个答案:

答案 0 :(得分:1)

一点Linq怎么样

var list =  AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).
                        Where(x => x.GetCustomAttributes(typeof(MyAttribute), false).Length > 0);

答案 1 :(得分:1)

IsDefined()很可能失败,因为Type.GetType("SomeAttribute")返回null。尝试将名称空间添加到属性名称:

Type.GetType("SomeNamespace.SomeAttribute")
相关问题