【发布时间】:2018-09-12 08:19:31
【问题描述】:
我目前正在阅读 C# 教程。现在我遇到了这个:
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle {
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
public double GetCost() {
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display() {
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
在class Tabletop 中有两次声明cost。一次为private double cost;,4 行后为double cost;
为什么会这样?
删除double cost; 时,代码仍然有效。当double cost 在代码中时,我可以将鼠标悬停在private double cost; 上并阅读消息:Tabletop.cost 字段从未使用过”。我几乎可以消除任何一个成本,并且代码工作正常。
- 他们是否忘记删除其中一个声明或背后有什么原因?
- 另外,为什么我没有收到“成本已定义”之类的错误消息?
【问题讨论】:
-
投票(+1)因为他们忘记删除它。两者都不重要,本来可以写
return GetArea() * 70; -
您的方法的成本会在您的班级中隐藏同名的成员。因此,您在方法中有效地使用了方法
cost,而在方法之外您可以访问该字段。这就是为什么当我打算使用字段而不是方法的值时,我更喜欢添加(冗余)this-qualifier。 -
您没有收到错误消息,因为它们在不同的范围内。
-
删除局部变量是必要的修复。当你放回去时,字段成本将始终保持为 0。可通过 Display() 观察。
标签: c# class inheritance declare