Home > Backend Development > C++ > How Can I Set a Property's Value Using Reflection When the Value is a String?

How Can I Set a Property's Value Using Reflection When the Value is a String?

Susan Sarandon
Release: 2025-01-20 10:37:09
Original
726 people have browsed it

How Can I Set a Property's Value Using Reflection When the Value is a String?

Use reflection to set string attribute values

Introduction: Programmatically manipulating objects through reflection often requires setting properties using assignments of various data types. This question explores a common situation: setting a property with a string value.

Question: Consider a Ship class that has a Latitude property of type double. Try setting this property using reflection, the code is as follows:

<code>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 fails with an ArgumentException because the string value cannot be converted directly to a double.

Solution: To resolve this issue, the string value must be explicitly converted to the correct type based on the PropertyInfo. A common tool for this purpose is Convert.ChangeType(). It uses runtime information to convert between IConvertible types.

The modified code using Convert.ChangeType() is:

<code>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

This code successfully sets the Latitude property to a converted double value.

The above is the detailed content of How Can I Set a Property's Value Using Reflection When the Value is a String?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template