Setting Property Values Using Reflection
It is possible to dynamically set the value of a property using reflection in C#. This allows you to modify an object's property at runtime, regardless of its accessibility or visibility.
To set a property value using reflection, follow these steps:
Here's an example that demonstrates how to use reflection to set the firstName property of a Person class:
using System; using System.Reflection; class Person { public string FirstName { get; set; } } class Test { static void Main(string[] args) { // Create an instance of the Person class Person p = new Person(); // Get the PropertyInfo object for the FirstName property var property = typeof(Person).GetProperty("FirstName"); // Set the value of the FirstName property using reflection property.SetValue(p, "John", null); // Print the value of the FirstName property Console.WriteLine(p.FirstName); // John } }
In this example, the property variable holds a reference to the FirstName property of the Person class. The SetValue method is invoked with the p instance and the string value "John" to set the property's value dynamically.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3