Home >Backend Development >C++ >Can C# Reflection Change Private Property Values from a String?
Can Reflection Alter Property Values from String Input?
Utilizing reflection in C#, you can access private members of a class, including its properties. This enables you to manipulate the underlying values of these properties, despite their access restrictions.
Example: Setting Property Values Reflectively
Consider the following code:
string propertyName = "first_name"; // Assume there's a property named first_name in the class
To set the value of this property using reflection, follow these steps:
Obtain the property info using Reflection:
Type propertyType = typeof(TargetClass); PropertyInfo propertyInfo = propertyType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance);
Utilize the SetValue method to alter the property value:
object targetObject = new TargetClass(); propertyInfo.SetValue(targetObject, "New Value", null);
Note: In the example above, TargetClass represents the class containing the first_name property. To access private or protected properties, adjust the BindingFlags in GetProperty() accordingly.
The above is the detailed content of Can C# Reflection Change Private Property Values from a String?. For more information, please follow other related articles on the PHP Chinese website!