Finding the attributes on the properties of an instance of a class
Posted
by Dan
on Stack Overflow
See other posts from Stack Overflow
or by Dan
Published on 2010-06-08T15:59:25Z
Indexed on
2010/06/08
16:02 UTC
Read the original article
Hit count: 226
c#
|reflection
Given an instance of a class I want to set properties on attributes at runtime.
So I tried this, but as far as I can tell this finds the attributes on the class not the instance, so any changes I make to the attribute properties have no effect.
var properties = myObject.GetType().GetProperties();
foreach (object prop in properties)
{
var attribute =prop.GetCustomAttributes(typeof(MyAttribute), true)[0];
//attribute.MyProp do some stuff
}
If I try using type descriptor like below, there is no way of getting to the attributes on the properties.
var myObject= (MyClass) object;
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(myObject);
//There is no props[0].GetCustomAttributes(
© Stack Overflow or respective owner