开发者

Find all classes with an attribute containing a specific property value

开发者 https://www.devze.com 2023-01-13 10:14 出处:网络
Is it possible to find a class that is tagged with a custom attribute based on a value given to that attribute?

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 attem开发者_开发问答pt -

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


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

0

精彩评论

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