Find all classes with an attribute containing a specific property value.

Is it possible to find a class marked with a special attribute based on the value given to this attribute?

Basically, I have classes that look like this:

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

From there I get all classes (Types) -

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

It all works. c contains all the relevant classes. Now I need to get a class from c with the MyAttr attribute and the value "CODE". The value is available through the MyAttr property, called Id .

It was my attempt -

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

This is not a trick. So, the real question is that this is possible, and if so, then what needs to be changed to get the corresponding class (and create an instance of it).

+6
reflection c # linq
source share
1 answer

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

+3
source share

All Articles