At runtime, how can I test whether a Property is readonly?

后端 未结 4 421
日久生厌
日久生厌 2021-01-05 01:06

I am auto-generating code that creates a winform dialog based on configuration (textboxes, dateTimePickers etc). The controls on these dialogs are populated from a saved da

相关标签:
4条回答
  • 2021-01-05 01:31

    I needed to use this for different classes, so I created this generic function:

    public static bool IsPropertyReadOnly<T>(string PropertyName)
    {
        MemberInfo info = typeof(T).GetMember(PropertyName)[0];
    
        ReadOnlyAttribute attribute = Attribute.GetCustomAttribute(info, typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;
    
        return (attribute != null && attribute.IsReadOnly);
    }
    
    0 讨论(0)
  • 2021-01-05 01:34

    With PropertyDescriptor, check IsReadOnly.

    With PropertyInfo, check CanWrite (and CanRead, for that matter).

    You may also want to check [ReadOnly(true)] in the case of PropertyInfo (but this is already handled with PropertyDescriptor):

     ReadOnlyAttribute attrib = Attribute.GetCustomAttribute(prop,
           typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;
     bool ro = !prop.CanWrite || (attrib != null && attrib.IsReadOnly);
    

    IMO, PropertyDescriptor is a better model to use here; it will allow custom models.

    0 讨论(0)
  • 2021-01-05 01:38

    I noticed that when using PropertyInfo, the CanWrite property is true even if the setter is private. This simple check worked for me:

    bool IsReadOnly = prop.SetMethod == null || !prop.SetMethod.IsPublic;
    
    0 讨论(0)
  • 2021-01-05 01:40

    Also - See Microsoft Page

    using System.ComponentModel;
    
    // Get the attributes for the property.
    
    AttributeCollection attributes = 
       TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
    
    // Check to see whether the value of the ReadOnlyAttribute is Yes.
    if(attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)) {
       // Insert code here.
    }
    
    0 讨论(0)
提交回复
热议问题