我遇到了一点问题,这个问题并没有通过一般可用的解决方案解决,看似同样的问题。从动态生成的类中获取属性
考虑:
我有一组动态生成的类,从已知的基类继承(让称之为BaseClass
)。 这些动态生成的类也具有动态生成的Properties
及其相关属性。
的属性也是一个自定义类的,虽然不是动态生成的:
[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
类型,不是castable到TypeAttribute
(如果我在VS调试器中检查实例,我可以看到包含的信息是为TypeAttribute
)。 我猜这是问题的症状,但我找不到原因 - 更不用说解决方案了。
有人可以指出为什么result
列表为空吗?
哦,这很有趣;那需要几分钟的时间才能为我建立一个测试平台......我希望有人能够在我这样做的时候发现一些明显的东西! –