One of the reflection applications: according to the control name, the property name is used to assign the value.

xiaoxiao2021-03-06  120

'Must refer to the namespace system.reflection, System.comPonentModel

'The following value according to the control name and attribute name

Public function getValueControlProperty (Byval ClassInstance Asbject, Byval controlName as string) AS Object

Dim Result As Object

DIM mytype as type = classinstance.gettype

Dim MyfieldInfo as FieldInfo = Mytype.Getfield ("_" & controlname, bindingflags.nonpublic OR_

Bindingflags.instance or bindingflags.public or bindingflags.instance)

IF not myfieldinfo is nothing then

DIM Properties as PropertyDescriptorCollection = typeDescriptor.getProperties (MyTYPE)

DIM MyProperty As PropertyDescriptor = Properties.Find (PropertyName, FALSE)

IF not myproperty is nothing then

DIM CTR As Object

Ctr = myfieldinfo.getValue (ClassInstance)

Try

Result = MyProperty.getValue (CTR)

Catch exception

MSGBOX (ex.Message)

END TRY

END IF

END IF

Return RESULT

END FUNCTION

'The following assignments according to the control name and attribute name

Public Function SetValueControlprolProperty (Byval CLassinstance As String, Byval PropertyName As String, Byval Value As Object) AS Object

Dim Result As Object

DIM mytype as type = classinstance.gettype

Dim myfieldInfo as fieldInfo = mytype.getfield ("_" & controlname, bindingflags.nonpublic_

OR bindingflags.instance or bindingflags.public or bindingflags.instance) 'add "_" this is a special

IF not myfieldinfo is nothing then

DIM Properties as PropertyDescriptorCollection = typeDescriptor.getProperties (MyTYPE)

DIM MyProperty As PropertyDescriptor = Properties.Find (PropertyName, False) 'This is set to true if you don't have to write.

IF not myproperty is nothing then

DIM CTR As Object

CTR = myfieldinfo.getValue (classinstance) 'acquired an example

Try

MyProperty.SetValue (CTR, VALUE) Result = CTR

Catch exception

MSGBOX (ex.Message)

END TRY

END IF

END IF

Return RESULT

END FUNCTION

'transfer

'The following implementation label1.text = textbox1.text, label2.text = TextBox2

Private sub button1_click (byvale as system.object, byval e as system.eventargs) Handles Button1.click

DIM I as integer

For i = 1 to 2

Me.SetValueControlProperty (ME, "Label" & i.tostring, "text", getValueControlProperty (ME, "TextBox" & I.toString, "Text"))

Next i

End Sub

转载请注明原文地址:https://www.9cbs.com/read-126574.html

New Post(0)