Using Reflection to Set Property Values with String Inputs in C#
Manipulating objects often requires setting property values dynamically, even when those values are initially provided as strings. This can be tricky when the property's type differs from the string. Directly using SetValue()
with a type mismatch results in an ArgumentException
.
Consider updating a Ship
object's "Latitude" property (a numeric type) using the string "5.5". The solution lies in converting the string to the correct data type before assignment. Convert.ChangeType()
is ideal for this runtime type conversion.
Here's how to implement this solution:
<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>
This code leverages runtime type information from propertyInfo.PropertyType
to correctly convert the string "5.5" before setting the "Latitude" property. This approach effectively handles various property types, providing a robust solution for dynamic property value assignment using string inputs.
The above is the detailed content of How Can I Set Property Values Using Reflection with String Inputs in C#?. For more information, please follow other related articles on the PHP Chinese website!