【发布时间】:2019-06-21 09:06:43
【问题描述】:
我正在学习继承,我理解下面的代码。
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;
非常感谢,
阿米尔
【问题讨论】:
-
更好的做法是简单地这样做是什么让你认为它“更好”?只是不一样
-
根据这些二传手的工作量,使用其中一个可能是一个更好的主意。一般来说,您应该为某种数据使用属性,并使用一种方法来实际执行一个动作。但没有任何规则强迫你这样做。
-
看起来“他们”的灵感来自于 Java。 IMO,99.99% 的 C# 开发人员不会在这里使用
set方法。 -
说了我所说的,这里有 nio “正确”或“错误”的答案。您喜欢哪种风格非常基于意见。
-
这段代码看起来像是java开发者在尝试学习C#
标签: c# inheritance methods multiple-inheritance access-modifiers