Home >Backend Development >C++ >Can C# Reflection Change Private Property Values from a String?

Can C# Reflection Change Private Property Values from a String?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 03:25:39591browse

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:

  1. Obtain the property info using Reflection:

    Type propertyType = typeof(TargetClass);
    PropertyInfo propertyInfo = propertyType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance);
  2. 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!

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