破坏Private

先看一段代码

static void Main ( )
{
var test1 = new Test1();
test1.Property1=3;
Console.ReadKey ( );
}
class Test1
{
private int Property1 { get; set; }
}

test1.Property1=3;必定编译错误。private有访问级别的限制。

代码修改后

static void Main ( )
{
var test1 = new Test1();
Type type1=test1.GetType();
PropertyInfo pi=type1.GetProperty("Property1", BindingFlags.Instance | BindingFlags.NonPublic);
pi.SetValue(test1,3,null);
test1.Show();
Console.ReadKey ( );
}
class Test1
{
private int Property1 { get; set; }
public Show(){
Console.WriteLine(Property1);
}
}

使用反射就能成功的修改test1中的私有Property1。在反射面前private的保护失效。

不过如果真的需要访问Private数据,还是调用那个类提供的对应Set函数,比如这样:

class Test1
{
public int Property1 { set{
field=value;
}}

private int field;
public Show(){
Console.WriteLine(field);
}
}

这种使用反射的使用方式破坏了类的封装性,最好不要用。

原文地址:https://www.cnblogs.com/ganmuren/p/2338079.html