How to set object property through Reflection [duplicate]
I'm trying to code a method that will accept the following 3 arguments:
an Object (user defined type which will vary)
a string representing a property name for that object
a string value, which will have to be converted from a string to the property's data type prior to assignment.
The method signature will look like this:
public void UpdateProperty(Object obj, string propertyName, string value)
I've found how to retrieve a property value with Reflection with the following code:
PropertyInfo[] properties = target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in properties)
{
if (string.Compare(prop.Name, propertyName, true) == 0)
{
return prop.GetValue(target, null).ToString();
}
}
The problem is that I can't f开发者_如何学运维igure out how to set the property value. Also, the value is coming in as a string, so I have to check the data type of the value against the property's datatype before it can be cast & assigned.
Any help would be greatly appreciated.
SetValue with Convert.ChangeType should work for you. Using your code:
newValue = Convert.ChangeType(givenValue, prop.PropertyType);
prop.SetValue(target, newValue, null);
SetValue is what you are looking for.
There are plenty of questions on here with sample code (take a look at the Related Question list on the right of this page)
e.g. Setting a property by reflection with a string value
prop.SetValue(target,new TypeConverter().ConvertFromString(propertyValue));
精彩评论