Question:
Is it feasible to use reflection to alter a property's value in C#, given that the property name is known?
Answer:
Absolutely, reflection enables this functionality. Here's how to achieve it:
using System; 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 } }
Note: If the target property is non-public, you'll need to employ BindingFlags.NonPublic | BindingFlags.Instance when fetching the property.
The above is the detailed content of Can Reflection Change a C# Property's Value Given its Name?. For more information, please follow other related articles on the PHP Chinese website!