Home >Backend Development >C++ >How Can I Set Property Values Dynamically in C# Using Reflection?

How Can I Set Property Values Dynamically in C# Using Reflection?

DDD
DDDOriginal
2025-01-05 08:03:42959browse

How Can I Set Property Values Dynamically in C# Using Reflection?

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:

  1. Get the PropertyInfo Object: Use Type.GetProperty to retrieve the PropertyInfo object associated with the property you want to modify. If the property is not public, you may need to specify additional binding flags, such as BindingFlags.NonPublic or BindingFlags.Instance.
  2. Invoke the SetValue Method: Once you have the PropertyInfo object, invoke its SetValue method to actually set the value of the property. This method takes two parameters: the object instance you want to modify and the new value to set.

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.

The above is the detailed content of How Can I Set Property Values Dynamically in C# Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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