简体   繁体   中英

How to invoke method, using reflection, on instantiated object?

I have some base objects "Car", "dog", "cat" they implement an interface "IGWUIElement". I have a list of these interfaces: List myList.

At runtime I loop through the list of my elements and by examining the name of the class (using reflection) i need to populate their properties - which are not a part of the interface). I have an xml document descripting the propeties and the value i should assign to them. Here is my interface instantiation.

IGWUIElement newUIElement = (IGWUIElement)Activator.CreateInstance(result);

How do I go about invoking the properties from their name with a particular value (Please note datatypes are limited to int and string). Each object have different properties.

Hope this makes sense...

/H4mm3r

Use PropertyInfo.SetValue()

PropertyInfo piInstance = typeof(IGWUIElement).GetProperty("property_name");
piInstance.SetValue(newUIElement, value, null);

More on msdn .

You can do this like so:

IGWUIElement element = myList[0];

// Set a string property
element.GetType().InvokeMember("SomeStringProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, element, "The String Value");

// Set an int property
element.GetType().InvokeMember("SomeIntProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, Type.DefaultBinder, element, 3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM