Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload