开发者

Identifying all types with some attribute

I have an issue with .Net reflection. The concept is fairly new to me and I'm exploring it with some test cases to see what works and what doesn't. I'm constructing an example wherein I populate a set of menus dynamically by scanning through my Types' attributes.

Basically, I want to find every type in my main namespace that declares 'SomeAttribute' (doesn't matter what it is, it doesn't have any members at present). What I've done is:

    For Each itemtype As Type In Reflection.Assembly.GetExecutingAssembly().GetTypes
        If itemtype.IsDefined(Type.GetType("SomeAttribute"), False) Then
            'd开发者_如何学Goo something with the type
        End If
    Next

This crashes the application on startup - the first type it identifies is MyApplication which is fairly obviously not what I want. Is there a right and proper way to look for all the 'real' 'sensible' types - i.e. classes that I've defined - within the current assembly?


It is most likely that IsDefined() fails since Type.GetType("SomeAttribute") returns null. Try adding the namespace to the attribute name:

Type.GetType("SomeNamespace.SomeAttribute")


How about a little Linq

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜