Find all classes with an attribute containing a specific property value

蓝咒 提交于 2020-01-13 09:46:08

问题


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:


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



来源:https://stackoverflow.com/questions/3576879/find-all-classes-with-an-attribute-containing-a-specific-property-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!