C#继承与方法
我正在学习继承,我理解下面的代码C#继承与方法,c#,inheritance,methods,multiple-inheritance,access-modifiers,C#,Inheritance,Methods,Multiple Inheritance,Access Modifiers,我正在学习继承,我理解下面的代码 namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int heig
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;
非常感谢,
Amir我相信其他人会提供不同的观点,但下面是我使用get/set的两个主要原因。如果这些不适用于给定的属性,那么很可能我不会使用getter/setter 1-调试
如果您可以调试所关心的setter,那么调试数据传播(数据如何传递)将非常容易。您可以很容易地抛出一个
调试。打印调用并调试正在设置的值,如果您担心它传递了错误的值。或者您可以放置断点并实际调试堆栈跟踪。例如:
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;
}
虽然我个人更喜欢使用属性get/set,但这只是我的偏好
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
}
更好的实践就是这么做,什么让你认为这是“更好的”?只是不同,取决于二传手做了多少,使用一个可能比另一个更好。通常,您应该为某些类型的数据使用属性,并使用方法来实际执行操作。但是没有规则强迫你这么做,看起来“他们”的灵感来自Java。在我看来,99.99%的C#dev不会在这里使用set
方法。我已经说过了,这里的答案是“正确”或“错误”。您喜欢哪种风格,这是基于opinipn的。这段代码看起来像是java开发人员试图学习C#
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
}