Notes for modifying object attributes using reflection

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.