Use reflection to set string type attribute value
When using reflection to set a string type attribute value, if the target attribute expects other types, it may cause an ArgumentException exception.
Solution: Use Convert.ChangeType() for dynamic type conversion
To solve this problem, you can use the Convert.ChangeType() method. This method uses runtime information to convert data types. However, it is important to note that not all conversions are possible.
Code example:
Consider the following code snippet:
<code class="language-csharp">Ship ship = new Ship(); string value = "5.5"; PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);</code>
propertyInfo = ship.GetType().GetProperty("Latitude")
Get "Latitude" attribute information. Convert.ChangeType(value, propertyInfo.PropertyType)
Converts the string "5.5" to a double precision floating point number, which matches the attribute type. propertyInfo.SetValue(ship, ..., null)
Set the attribute to the converted value. Note: This solution assumes no exception handling or special case logic for types that cannot be converted directly using Convert.ChangeType().
The above is the detailed content of How to Safely Set String Property Values Using Reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!