Introduction: Programmatically manipulating objects through reflection often requires setting properties using assignments of various data types. This question explores a common situation: setting a property with a string value.
Question: Consider a Ship class that has a Latitude property of type double. Try setting this property using reflection, the code is as follows:
<code>Ship ship = new Ship(); string value = "5.5"; PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship, value, null);</code>
However, this code fails with an ArgumentException because the string value cannot be converted directly to a double.
Solution: To resolve this issue, the string value must be explicitly converted to the correct type based on the PropertyInfo. A common tool for this purpose is Convert.ChangeType(). It uses runtime information to convert between IConvertible types.
The modified code using Convert.ChangeType() is:
<code>Ship ship = new Ship(); string value = "5.5"; PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);</code>
This code successfully sets the Latitude property to a converted double value.
The above is the detailed content of How Can I Set a Property's Value Using Reflection When the Value is a String?. For more information, please follow other related articles on the PHP Chinese website!