Utilizing Reflection to Modify Property Values
Reflection, a powerful .NET framework feature, grants the ability to inspect and modify objects and their members dynamically. In this context, we'll explore how reflection can be leveraged to set the value of a specific property within a C# class.
Consider a scenario where you know the name of a property, such as "first_name," and wish to modify its value using this string. Reflection provides a solution to this problem.
To achieve the desired outcome, the following steps can be taken:
The provided code sample exemplifies this approach:
class Person { public string Name { get; set; } } class Test { static void Main(string[] arg) { Person p = new Person(); var property = typeof(Person).GetProperty("Name"); property.SetValue(p, "Jon", null); Console.WriteLine(p.Name); // Jon } }
If the property's accessibility is non-public, specify BindingFlags as shown:
var property = typeof(Person).GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
With the aid of reflection, setting property values dynamically becomes a feasible endeavor, offering flexibility in code manipulation and runtime behavior.
The above is the detailed content of How Can Reflection Be Used to Dynamically Set Property Values in C#?. For more information, please follow other related articles on the PHP Chinese website!