【发布时间】:2011-01-17 23:44:00
【问题描述】:
在某些情况下,我在类的顶部声明了成员变量,然后还声明了一个属性来访问或设置该成员变量,但我问自己该属性是否是必要的,如果它只是要被访问的变量并且从类内部设置,没有其他地方,那么使用属性访问和设置成员变量而不是直接对成员变量本身进行设置有什么好处。这是一个例子:
public class Car
{
int speed; //Is this sufficient enough if Car will only set and get it.
public Car(int initialSpeed)
{
speed = initialSpeed;
}
//Is this actually necessary, is it only for setting and getting the member
//variable or does it add some benefit to it, such as caching and if so,
//how does caching work with properties.
public int Speed
{
get{return speed;}
set{speed = value;}
}
//Which is better?
public void MultiplySpeed(int multiply)
{
speed = speed * multiply; //Line 1
this.Speed = this.Speed * multiply; //Line 2
//Change speed value many times
speed = speed + speed + speed;
speed = speed * speed;
speed = speed / 3;
speed = speed - 4;
}
}
在上面,如果我没有属性 Speed 来设置和获取变速,并且我决定将 int speed 更改为 int spd,那么我将不得不在任何使用它的地方将 speed 更改为 spd,但是,如果我使用诸如 Speed 之类的属性来设置和获取速度,我只需在属性的获取和设置中将 speed 更改为 spd,因此在我的 MutilplySpeed 方法中,类似于 this.Speed = this.Speed + this .Speed + this.Speed 不会中断。
【问题讨论】: