Home > Backend Development > C++ > How Can I Set Property Values Using Reflection with String Inputs in C#?

How Can I Set Property Values Using Reflection with String Inputs in C#?

Linda Hamilton
Release: 2025-01-20 10:41:08
Original
682 people have browsed it

How Can I Set Property Values Using Reflection with String Inputs in C#?

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

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!

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