欢迎光临
我们一直在努力

反射应用之一:根据控件名、属性名进行取值和赋值-.NET教程,.NET Framework

建站超值云服务器,限时71元/月

必须引用命名空间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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 反射应用之一:根据控件名、属性名进行取值和赋值-.NET教程,.NET Framework
分享到: 更多 (0)

相关推荐

  • 暂无文章