反射應(yīng)用之一:根據(jù)控件名、屬性名進(jìn)行取值和賦值
2024-07-21 02:17:06
供稿:網(wǎng)友
 
'必須引用命名空間system.reflection,system.componentmodel
 '以下根據(jù)控件名和屬性名取值
 public function getvaluecontrolproperty(byval classinstance as object, byval controlname as string, byval propertyname 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 ex as exception
 msgbox(ex.message)
 end try
 end if
 end if
 return result
 end function
 '以下根據(jù)控件名和屬性名賦值
 public function setvaluecontrolproperty(byval classinstance as object, byval controlname 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) '加"_"這個(gè)是特要緊的
 if not myfieldinfo is nothing then
 dim properties as propertydescriptorcollection = typedescriptor.getproperties(mytype)
 dim myproperty as propertydescriptor = properties.find(propertyname, false) '這里設(shè)為true就不用區(qū)分大小寫了
 if not myproperty is nothing then
 dim ctr as object
 ctr = myfieldinfo.getvalue(classinstance) '取得控件實(shí)例
 try
 myproperty.setvalue(ctr, value)
 result = ctr
 catch ex as exception
 msgbox(ex.message)
 end try
 end if
 end if
 return result
 end function
 '調(diào)用
 '以下實(shí)現(xiàn)label1.text=textbox1.text,label2.text=textbox2
 private sub button1_click(byval sender 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