我正在学习继承,并且了解下面的代码。
namespace InheritanceApplication {
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
// Base class PaintCost
public interface PaintCost {
int getCost(int area);
}
// Derived class
class Rectangle : Shape, PaintCost {
public int getArea() {
return (width * height);
}
public int getCost(int area) {
return area * 70;
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
但是,为什么他们要创建设定高度和设定宽度功能。简单地做到这一点不是更好的做法:
public int width {get;set;}
public int height {get;set;}
然后在主类中执行以下操作:
rect.width = 5;
rect.height = 7;
非常感谢,
阿米尔
答案 0 :(得分:0)
我确定其他人会提供不同的观点,但这是我使用获取/设置的两个主要理由。如果这些都不适用于给定的属性,那么我很可能不会使用getters / setters。
1-调试
如果您可以调试所关注的设置器,那么它将大大简化调试数据传播(如何传递数据)的过程。如果您担心传递给错误的值,可以轻松地发起Debug.Print
调用并调试所设置的值。或者,您可以放置断点并通过堆栈跟踪进行实际调试。例如:
class Shape {
public void setWidth(int w) {
if(w < 0)
Debug.Print("width is less than 0!");
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}
2-值更改操作
可能有更好的方法来实现此目的,但是我喜欢能够向设置器添加简单的逻辑,以确保值更改时需要运行的任何逻辑都可以执行。例如,我可以使用以下内容:
public void SetWindowHeight(int newHeight)
{
if(WindowHeight == newHeight)
return;
WindowHeight = newHeight;
UpdateWindowDisplay();
}
public int GetWindowHeight()
{
return WindowHeight;
}
private int WindowHeight;
public void UpdateWindowDisplay()
{
Window.UpdateHeight(WindowHeight);
// Other window display logic
}
虽然我个人更喜欢使用属性获取/设置,但这只是我的偏好。
public int WindowHeight
{
get
{
return windowHeight;
}
set
{
if(windowHeight == value)
return;
windowHeight = value;
UpdateWindowDisplay();
}
}
private int windowHeight;
public void UpdateWindowDisplay()
{
Window.UpdateHeight(WindowHeight);
// Other window display logic
}