Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all classes with an attribute containing a specific property value

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).

like image 233
mld Avatar asked Aug 26 '10 15:08

mld


1 Answers

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

like image 168
SLaks Avatar answered Nov 12 '22 01:11

SLaks