我遇到了一个小问题,通常的解决方案似乎不能解决它。
请考虑:
我有一组动态生成的类,继承自一个已知的基类(我们称之为BaseClass
)。
这些动态生成的类还具有动态生成的属性
及其关联属性。
这些属性也是一个自定义类,但不是动态生成的:
[AttributeUsage(AttributeTargets.Property)]
class TypeAttribute: Attribute
{
private Type _type;
public Type Type
{
get { return _type; }
}
public TypeAttribute(Type t)
{
_type = t;
}
}
然后我想在运行时获取已分配属性的值:
List<PropertyInfo> result = target.GetType()
.GetProperties()
.Where(
p =>
p.GetCustomAttributes(typeof(TypeAttribute), true)
//.Where(ca => ((TypeAttribute)ca).)
.Any()
)
.ToList();
其中target
是BaseClass
的子类。但是,列表result
为空,这让我感到困惑。
我使用以下方式添加属性:
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName,
PropertyAttributes.HasDefault, propertyType, null);
ConstructorInfo classCtorInfo = typeof(TypeAttribute).
GetConstructor(new Type[] { typeof(Type) });
CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder(
classCtorInfo, new object[] { getType(dataType) });
propertyBuilder.SetCustomAttribute(myCABuilder);
其中dataType
是要存储在属性中的类型,tb
是类的TypeBuilder
。
如果我在属性上执行getCustomAttributes()
,我会得到期望的属性,除了我要找的那个。但是如果我执行getCustomAttributesData()
,我会得到所有属性,但我要找的那个是CustomAttributeData
类型的,无法转换为TypeAttribute
(如果我在VS调试器中检查实例,我可以看到包含信息是TypeAttribute
)。
我猜这是问题的症状,但我找不到原因,更不用说解决方法了。
有人能告诉我为什么result
列表为空吗?