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
Release: 2025-01-05 03:25:39
Original
627 people have browsed it

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

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);
    Copy after login
  2. Utilize the SetValue method to alter the property value:

    object targetObject = new TargetClass();
    propertyInfo.SetValue(targetObject, "New Value", null);
    Copy after login

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!

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