我试图做的是调用属性的方法,使用反射的方法。我有原始的控件(一个ComboBox),属性的PropertyInfo(ComboBox.Items)和方法名称(ComboBox.Items.Add)。我试过下面的代码来获取,修改,设置,但它不起作用,因为Items没有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
有没有人有任何建议?
感谢
正如一个建议,如果你有兴趣在通过反射更容易这样的拨打电话和使用C#4,你可能希望在DynamicObject来包装这个反射功能。我写了一个关于如何做到这一点在这里发布:http://mattmc3.blogspot.com/2011/03/fun-with-dynamicobject-and-making-net.html – mattmc3 2011-03-21 15:27:24
哦,我要看看谢谢! – acron 2011-03-22 09:04:50