Home > Backend Development > C++ > How to Set Property Values Using Reflection with String Inputs?

How to Set Property Values Using Reflection with String Inputs?

DDD
Release: 2025-01-20 10:27:10
Original
557 people have browsed it

How to Set Property Values Using Reflection with String Inputs?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template