繁体   English   中英

C#继承和方法

[英]C# Inheritance and Methods

我正在学习继承,并且了解下面的代码。

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;

非常感谢,

阿米尔

我确定其他人会提供不同的观点,但这是我使用获取/设置的2个主要原因。 如果这些都不适用于给定的属性,那么我将不会使用getters / setter方法。

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM