0

我对 .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 ,这显然不是我想要的。在当前程序集中寻找所有“真正的”“合理”类型——即我定义的类——是否有正确的方法?

4

2 回答 2

1

小Linq怎么样

var list =  AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).
                        Where(x => x.GetCustomAttributes(typeof(MyAttribute), false).Length > 0);
于 2010-04-10T10:43:35.277 回答
1

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

Type.GetType("SomeNamespace.SomeAttribute")
于 2010-04-10T10:43:56.353 回答