I have run in to a little bit of a problem which is not solved by the generally available solutions to seemingly the same problem.
Consider:
I have a set of dynamically generated classes, inheriting from a known base Class (lets call it BaseClass).
These dynamically generated classes also have dynamically generated Properties with associated attributes.
The attributes are also of a custom class, though not dynamically generated:
[AttributeUsage(AttributeTargets.Property)]
class TypeAttribute: Attribute
{
private Type _type;
public Type Type
{
get { return _type; }
}
public TypeAttribute(Type t)
{
_type = t;
}
}
Then I want to, runtime of course, fetch the value of this assigned attribute:
List<PropertyInfo> result = target.GetType()
.GetProperties()
.Where(
p =>
p.GetCustomAttributes(typeof(TypeAttribute), true)
//.Where(ca => ((TypeAttribute)ca).)
.Any()
)
.ToList();
where target is a subclass of BaseClass. The List result is however empty, and this baffles me.
I add the attribute using
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);
where dataType is the type to store in the attribute and tb is the TypeBuilder for the class.
If I do getCustomAttributes() on the property, I get the expected attributes except the one I'm looking for. But if I do getCustomAttributesData() I get all of them, but the one I'm looking for is of type CustomAttributeData and is not castable to TypeAttribute (if i examine the instance in the VS debugger i can see that the contained information is for a TypeAttribute).
I'm guessing that this is a symptom of the problem, but I cannot find the cause - much less the solution.
Can anybody point out to me why the result list is empty?