Home > Backend Development > C++ > How Can Reflection Be Used to Dynamically Set Property Values in C#?

How Can Reflection Be Used to Dynamically Set Property Values in C#?

DDD
Release: 2025-01-04 06:45:40
Original
286 people have browsed it

How Can Reflection Be Used to Dynamically Set Property Values in C#?

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:

  1. Fetch the Property Using Type.GetProperty: Utilize Type.GetProperty to obtain the property's metadata. Binding flags may be required if the property is not public.
  2. Set the Value Via SetValue: Call the SetValue method on the retrieved property to assign the desired value. An object instance is required to call SetValue.

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

If the property's accessibility is non-public, specify BindingFlags as shown:

var property = typeof(Person).GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template