查找具有包含特定属性值的属性的所有类 [英] Find all classes with an attribute containing a specific property value

查看:76
本文介绍了查找具有包含特定属性值的属性的所有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能基于赋予该属性的值来找到一个用自定义属性标记的类?

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

这一切似乎奏效. c包含所有适当的类.现在,我需要从c获取具有属性MyAttr和值"CODE"的类.该值可通过MyAttr上名为Id的属性获得.

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.

这是我的尝试-

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

推荐答案

Assembly.GetExecutingAssembly()替换为typeof(AbstractParentClass).Assembly.

这篇关于查找具有包含特定属性值的属性的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆