C#通过反射修改私有变量的值
代码
class Program
{
static void Main(string[] args)
{
Person p = new Person();
Console.WriteLine(p.Name);
var a = p.GetType().GetField("_name",
BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.ExactBinding);
a.SetValue(p, "ghy");
Console.WriteLine(p.Name);
}
}
public class Person
{
private string _name = "Henley";
public string Name { get; private set; }
}
{
static void Main(string[] args)
{
Person p = new Person();
Console.WriteLine(p.Name);
var a = p.GetType().GetField("_name",
BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.ExactBinding);
a.SetValue(p, "ghy");
Console.WriteLine(p.Name);
}
}
public class Person
{
private string _name = "Henley";
public string Name { get; private set; }
}