相关疑难解决方法(0)

Reflection是否打破了封装原则?

好吧,假设我们有一个类定义的类

public class TestClass
{
    private string MyPrivateProperty { get; set; }

    // This is for testing purposes
    public string GetMyProperty()
    {
        return MyPrivateProperty;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们尝试:

TestClass t = new TestClass { MyPrivateProperty = "test" };
Run Code Online (Sandbox Code Playgroud)

TestClass.MyPrivateProperty is inaccessible due to its protection level正如预期的那样,编译失败.

尝试

TestClass t = new TestClass();
t.MyPrivateProperty = "test";
Run Code Online (Sandbox Code Playgroud)

并使用相同的消息再次编译失败.

一切都很好,直到现在,我们都在期待这一点.

但后来写道:

PropertyInfo aProp = t.GetType().GetProperty(
        "MyPrivateProperty",
        BindingFlags.NonPublic | BindingFlags.Instance);

// This works:
aProp.SetValue(t, "test", null);

// Check
Console.WriteLine(t.GetMyProperty());
Run Code Online (Sandbox Code Playgroud)

在这里,我们设法改变了一个私人领域.

仅使用反射能够改变某个物体的内部状态是不是不正常?

编辑:

感谢到目前为止的回复.对于那些说"你不必使用它"的人:那个班级设计师怎么样,看起来他再也不能承担内部的国家安全了?

c# oop reflection

10
推荐指数
2
解决办法
2264
查看次数

标签 统计

c# ×1

oop ×1

reflection ×1