Set the string value of an attribute using reflection
When setting properties using reflection, you may encounter an ArgumentException due to type mismatch. To resolve this issue, consider the following:
Method 1: Convert.ChangeType()
This method allows conversion between compatible types at runtime. For non-IConvertible types, special case logic may be required.
Code example:
Ship ship = new Ship(); string value = "5.5"; PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
The above is the detailed content of How to Safely Set a String Value to a Property Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!