Use reflection to set string attribute values
Setting property values using reflection and string values can be tricky because type conversions may be required.
Suppose there is a Ship class, which has a property called Latitude of type double. The following code attempts to set this property to the string value "5.5":
<code class="language-csharp">Ship ship = new Ship(); string value = "5.5"; PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship, value, null);</code>
However, this code will throw an ArgumentException because the string value cannot be directly converted to the double type.
To solve this problem, you can use Convert.ChangeType() for type conversion. This function allows you to convert values based on runtime information of the target type. The following code demonstrates this approach:
<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>
By using Convert.ChangeType(), the string value is successfully converted to double type and assigned to the Latitude property. Note that if some specific types of conversions are not supported, you may need to handle exceptions or implement special case logic.
The above is the detailed content of How to Set Property Values Using Reflection with String Inputs?. For more information, please follow other related articles on the PHP Chinese website!