首页 > 开发 > 综合 > 正文

反射应用之一:根据控件名、属性名进行取值和赋值

2024-07-21 02:17:06
字体:
来源:转载
供稿:网友
'必须引用命名空间system.reflection,system.componentmodel

'以下根据控件名和属性名取值

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

'以下根据控件名和属性名赋值

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) '加"_"这个是特要紧的

if not myfieldinfo is nothing then

dim properties as propertydescriptorcollection = typedescriptor.getproperties(mytype)

dim myproperty as propertydescriptor = properties.find(propertyname, false) '这里设为true就不用区分大小写了

if not myproperty is nothing then

dim ctr as object

ctr = myfieldinfo.getvalue(classinstance) '取得控件实例

try

myproperty.setvalue(ctr, value)

result = ctr

catch ex as exception

msgbox(ex.message)

end try

end if

end if

return result

end function

'调用

'以下实现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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表