Home >Backend Development >C++ >How to Safely Set String Property Values Using Reflection in C#?

How to Safely Set String Property Values Using Reflection in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-20 10:38:09790browse

How to Safely Set String Property Values Using Reflection in C#?

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>
  1. Get attributes: propertyInfo = ship.GetType().GetProperty("Latitude") Get "Latitude" attribute information.
  2. Convert string value: Convert.ChangeType(value, propertyInfo.PropertyType) Converts the string "5.5" to a double precision floating point number, which matches the attribute type.
  3. Set attribute value: 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn