C# setting property values through reflection with attributes

后端 未结 1 1599
小蘑菇
小蘑菇 2020-12-23 22:33

I am trying to build an object through an attribute on a classes property that specifies a column in a supplied data row that is the value of the property, as below:

相关标签:
1条回答
  • 2020-12-23 23:14

    There are a couple of separate issues here

    • typeof(MyClass).GetCustomAttributes(bool) (or GetType().GetCustomAttributes(bool)) returns the attributes on the class itself, not the attributes on members. You will have to invoke typeof(MyClass).GetProperties() to get a list of properties in the class, and then check each of them.

    • Once you got the property, I think you should use Attribute.GetCustomAttribute() instead of MemberInfo.GetGustomAttributes() since you exactly know what attribute you are looking for.

    Here's a little code snippet to help you start:

    PropertyInfo[] properties = typeof(MyClass).GetProperties();
    foreach(PropertyInfo property in properties)
    {
        StoredDataValueAttribute attribute =
            Attribute.GetCustomAttribute(property, typeof(StoredDataValueAttribute)) as StoredDataValueAttribute;
    
        if (attribute != null) // This property has a StoredDataValueAttribute
        {
             property.SetValue(instanceOfMyClass, attribute.DataValue, null); // null means no indexes
        }
    }
    

    EDIT: Don't forget that Type.GetProperties() only returns public properties by default. You will have to use Type.GetProperties(BindingFlags) to get other sorts of properties as well.

    0 讨论(0)
提交回复
热议问题