Find all classes with an attribute containing a sp

2019-04-28 03:19发布

Is it possible to find a class that is tagged with a custom attribute based on a value given to that attribute?

Basically, I have classes that look like this -

[MyAttr("CODE")]
public class MyClass() {}

From there I'm getting all the classes (Types) -

var c = Assembly.GetExecutingAssembly().GetTypes().Where
                        (
                            t => t.IsClass && 
                            t.Namespace == (typeof(AbstractParentClass)).Namespace &&
                            t.IsSubclassOf(typeof(AbstractParentClass))
                        );

This all appears to work. c contains all of the appropriate classes. Now I need to get the class from c that has attribute MyAttr and the value "CODE". The value is available via a property on MyAttr called Id.

This was my attempt -

var message = from m in c
                  from a in m.GetCustomAttributes(typeof(MyAttr), false)
                  where ((MyAttr)a).Id == "CODE"
              select m;

That didn't do the trick. So, the real question is if this is even possible and if so what needs to be changed to get the appropriate class (and instantiate it).

1条回答
别忘想泡老子
2楼-- · 2019-04-28 03:56

Replace Assembly.GetExecutingAssembly() with typeof(AbstractParentClass).Assembly.

查看更多
登录 后发表回答