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

后端 未结 4 423
日久生厌
日久生厌 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(string PropertyName)
    {
        MemberInfo info = typeof(T).GetMember(PropertyName)[0];
    
        ReadOnlyAttribute attribute = Attribute.GetCustomAttribute(info, typeof(ReadOnlyAttribute)) as ReadOnlyAttribute;
    
        return (attribute != null && attribute.IsReadOnly);
    }
    

提交回复
热议问题