属性和封装 [英] Property and Encapsulation

查看:74
本文介绍了属性和封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是有关在类中使用属​​性的问题.

Following is a question regarding using properties in class.

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

I have been using public properties instead of exposing member variables publically. Majority advise that this approach helps encapsulation. However, I don’t understand the encapsulation advantage by making it a property.

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

many people donot know the real reason for using properties. They just do it as part of coding standard.

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

Can someone clearly explain how a property is better than public member variable and how it improves encapsulation?

推荐答案

封装可通过隔离调用类免受更改来提供帮助.

Encapsulation helps by insulating calling classes from changes.

让我们想象一下,您有一个用于模拟汽车引擎的简单类(因为所有OO示例都应涉及汽车类比:)).您可能有一个简单的字段,如下所示:

Let's imagine you have a simple class that models a car engine (cause all OO examples should involve a car analogy :) ). You may have a simple field like this:

private bool engineRunning;

仅公开此字段或提供IsEngineRunning()getter似乎没有什么不同.

Simply making this field public or providing an IsEngineRunning() getter doesn't appear to be any different.

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

Now suppose you make your class more sophisticated, you want to remove that field and replace it with:

private bool ignitionOn;
private bool starterWasActivated;

现在,如果您有很多类可以访问旧的engineRunning字段,则必须去做所有更改(不好的时候).

Now if you have lots of classes accessing the old engineRunning field you have to go and change them all (bad times).

如果相反,您是从以下地方开始的:

If instead you had started with:

public bool IsEngineRunning()
{
    return this.engineRunning;
}

您现在可以将其更改为:

you could now change it to :

public bool IsEngineRunning()
{
    return ignitionOn && starterWasActivated;
}

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

and the class's interface remains the same (good times).

这篇关于属性和封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆