Using Reflection to call a method of a property

2020-08-10 19:27发布

问题:

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?

Thanks

回答1:

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

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

...and it worked :P



回答2:

@acron, Thanks for providing a great question and answer. I want to extend your solution for a slightly different scenario for anyone looking in the future.

Facing a similar problem in the ASP.NET world I was trying to find a common way to load either a System.Web.UI.Webcontrols.DropDownList OR a System.Web.UI.HtmlControls.HtmlSelect While both of these have an "Items" property of type "ListItemCollection", with a corresponding "Add" method, they do not share a common interface (as they SHOULD... hey Microsoft...) so that casting can be used.

The additional challenge that your solution didn't provide for is the overloading of the Add method.

Without the overloads your line: MethodInfo m = p.PropertyType.GetMethod(methodName); works just fine. But, when the Add method is overloaded an additional parameter is called for so that the runtime can identify which overload to invoke.

MethodInfo methInfo = propInfo.PropertyType.GetMethod("Add", new Type[] { typeof(ListItem) });



回答3:

The error that you are getting indicates that the property in question is read only. There is no set method defined. You will not be able to set the value for the property without a setter.

Post back with the name of the property or more context and we may be able to give you a better answer or an alternative.