Home > Backend Development > C++ > Can Reflection Change a C# Property's Value Given its Name?

Can Reflection Change a C# Property's Value Given its Name?

Linda Hamilton
Release: 2025-01-03 17:31:39
Original
187 people have browsed it

Can Reflection Change a C# Property's Value Given its Name?

Setting Property Value Using Reflection

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:

  1. Fetch the Property: Utilize Type.GetProperty method to obtain the target property. You may need to specify additional binding flags to ensure accessibility.
  2. Set the Value: Invoke SetValue method on the retrieved property. Here's a code example to illustrate:
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
    }
}
Copy after login

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!

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