【发布时间】:2011-07-19 18:43:51
【问题描述】:
我想要做的是调用属性的方法,使用反射。我有原始控件(一个 ComboBox)、属性的 PropertyInfo(ComboBox.Items)和方法的名称(ComboBox.Items.Add)。我已经尝试使用下面的代码来获取、更改、设置,但它不起作用,因为 Items 没有设置器。
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
有人有什么建议吗?
谢谢
【问题讨论】:
-
作为一个建议,如果您有兴趣通过反射更轻松地进行此类调用并且使用 C# 4,您可能希望将此反射功能包装在 DynamicObject 中。我在这里写了一篇关于如何做到这一点的帖子:mattmc3.blogspot.com/2011/03/…
-
哦,我去看看,谢谢!
标签: c# .net reflection