使用反射调用属性的方法 [英] Using Reflection to call a method of a property

查看:109
本文介绍了使用反射调用属性的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做的是调用属性的方法,使用反射。我有原来的控制(一个ComboBox),属性的的PropertyInfo(ComboBox.Items)和方法的名称(ComboBox.Items.Add)。我试着下面的代码来获得,改变设置,但由于项目没有一个二传手这是行不通的。

What I'm trying to do is call the method of a property, using Reflection. I have the original Control (a ComboBox), the PropertyInfo of the property (ComboBox.Items) and the name of the method (ComboBox.Items.Add). I've tried the code below to get, alter, set but it doesn't work because Items doesn't have a setter.

PropertyInfo p  = controlType.GetProperty(propertyName); // gets the property ('Items')
MethodInfo m    = p.PropertyType.GetMethod(methodName); // gets the method ('Items.Add')
object o        = p.GetValue(newControl, null);         // gets the current 'Items'

m.Invoke(o, new object[] { newValue });                 // invokes 'Add' which works
p.SetValue(newControl, o, null);                         // exception: 'Items' has no setter



有没有人有任何意见

Does anyone have any advice?

感谢

推荐答案

这是快...我改变了调用行..

That was quick... I changed the Invoke line to...

m.Invoke(p.GetValue(newControl, null), new object[] { newValue });



...和它的工作:P

...and it worked :P

这篇关于使用反射调用属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆