在C#中,PropertyInfo.SetValue方法用于设置属性值。该方法接受两个参数:对象实例和属性值。下面是一个示例代码,演示如何使用PropertyInfo.SetValue方法设置属性值:
using System;
using System.Reflection;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "John";
person.Age = 30;
// 使用反射获取Person类的Type对象
Type personType = person.GetType();
// 获取Name属性的PropertyInfo对象
PropertyInfo namePropertyInfo = personType.GetProperty("Name");
// 设置Name属性的值
namePropertyInfo.SetValue(person, "Jane");
// 输出修改后的Name属性值
Console.WriteLine(person.Name); // 输出 "Jane"
}
}