属性和封装

Lij*_*ijo 5 oop encapsulation properties member-variables

以下是关于在课堂上使用属性的问题.

我一直在使用公共属性而不是公开地公开成员变量.多数人建议这种方法有助于封装.但是,我不了解封装的优势,使其成为一个属性.

很多人都不知道使用房产的真正原因.他们只是将其作为编码标准的一部分.

有人可以清楚地解释一个属性如何比公共成员变量更好以及它如何改善封装?

Pao*_*olo 6

封装有助于将调用类与变更隔离开来.

让我们假设您有一个简单的类来模拟汽车引擎(因为所有的OO示例都应该涉及汽车类比:)).你可能有一个像这样的简单字段:

private bool engineRunning;
Run Code Online (Sandbox Code Playgroud)

简单地将此字段设为公开或提供IsEngineRunning()getter似乎没有任何不同.

现在假设您使类更复杂,您想要删除该字段并将其替换为:

private bool ignitionOn;
private bool starterWasActivated;
Run Code Online (Sandbox Code Playgroud)

现在,如果你有很多课程访问旧engineRunning字段,你必须去更改它们(糟糕的时间).

相反,如果你开始:

public bool IsEngineRunning()
{
    return this.engineRunning;
}
Run Code Online (Sandbox Code Playgroud)

您现在可以将其更改为:

public bool IsEngineRunning()
{
    return ignitionOn && starterWasActivated;
}
Run Code Online (Sandbox Code Playgroud)

并且类的界面保持不变(好时光).


ova*_*riq 5

最好公开属性而不是成员变量,因为这样可以在设置或获取成员变量的值时进行各种检查。

假设你有一个成员变量:

private int id;
Run Code Online (Sandbox Code Playgroud)

你有一个公共财产:

public int ID
{
    get 
    { 
       // do something before returning
    }
    set 
    {
      // do some checking here may be limits or other kind of checking
    }
}
Run Code Online (Sandbox Code Playgroud)