Notes for modifying object attributes using reflection
Author: Xiao dye cream Lin drunk QQ: 51817 Email: pyeye@126.com reprint please indicate the source
As we all know, the following code can be used to dynamically set the visibility of object attributes:
Setpropertyvisibility (OBJ, "property name", true/false)
Set visible properties of object properties
1 Public Sub SetPropertyVisibility(obj As Object, propertyName As String, visible As Boolean)
2 Dim type As Type = GetType(BrowsableAttribute)
3 Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(obj)
4 Dim attrs As AttributeCollection = props(propertyName).Attributes
5 Dim fld As FieldInfo = type.GetField("browsable ", BindingFlags.Instance Or BindingFlags.NonPublic)
6 fld.SetValue(attrs(type), visible)
7 End Sub
8
Note: This function is used to search for fields in the object metadata and set attributes, therefore, if the attribute of an object does not contain browsable (true/false), this function cannot operate on it, and other attributes without this browsable parameter are not misled. The correct method is to add browsable in each attribute when you need to use this function. The default value is browsable (true) by default. It is also necessary to do so. Similar functions are:
Set the read-only attribute of the Object Property
1 Private Sub SetPropertyReadOnly(obj As Object, propertyName As String, [readOnly] As Boolean)
2 Dim type As Type = GetType(System.ComponentModel.ReadOnlyAttribute)
3 Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(obj)
4 Dim attrs As AttributeCollection = props(propertyName).Attributes
5 Dim fld As FieldInfo = type.GetField("isReadOnly", BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.CreateInstance)
6 fld.SetValue(attrs(type), [readOnly])
7 End Sub
8