【发布时间】:2020-02-13 06:10:20
【问题描述】:
考虑以下代码:
public class Counter
{
private int _value;
// public int Value => _value;
// commented for asking purposes
public void Increment() {
_value++;
}
public void Decrement() {
_value--;
}
public void CopyOtherCounter(Counter other)
{
_value = other._value;
// the compiler didn't show any error here
// why it does not break encapsulation?
}
}
我想问一下这是否意味着打破封装。
编辑:因为我认为我不应该能够读取其他对象私有值,即使它具有相同的类型。因为这可能发生:
public class Person {
private float _walletMoney; // no getter
private void StealFrom(Person other) {
_walletMoney += other._walletMoney; //reading other private wallet
other._walletMoney = 0; //writing other private wallet
}
}
void Main() {
var John = new Person();
var Bob = new Person();
John.StealFrom(Bob);
}
【问题讨论】:
-
为什么你认为它破坏了封装性?
-
通过创建公共方法和属性,您创建了公共表面积。其他代码可以使用这些公共表面区域与
Counter类进行交互。如果您的公共方法/属性更改任何不会违反封装原则的私有字段。 -
封装是将一个或多个项目(数据成员和方法)封装在一个物理或逻辑包中,对于 c# 来说,它是一个类。检查这个link