卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

C# 和多重继承

C# 和多重继承

C# 不支持多重继承。要实现多重继承,请使用接口。

这是类 Shape 中的接口 PaintCost -

'
public interface PaintCost {
   int getCost(int area);
}

形状是我们的基类,而矩形是派生类 -

'
class Rectangle : Shape, PaintCost {
   public int getArea() {
      return (width * height);
   }
   public int getCost(int area) {
      return area * 80;
   }
}

现在让我们看看在 C# 中实现多重继承接口的完整代码 -

'
Using System;
namespace MyInheritance {
   class Shape {
      public void setWidth(int w) {
         width = w;
      }
      public void setHeight(int h) {
         height = h;
      }
      protected int width;
      protected int height;
   }
   public interface PaintCost {
      int getCost(int area);
   }
   class Rectangle : Shape, PaintCost {
      public int getArea() {
         return (width * height);
      }

      public int getCost(int area) {
         return area * 80;
      }
   }
   class RectangleDemo {
      static void Main(string[] args) {
         Rectangle Rect = new Rectangle();
         int area;
         Rect.setWidth(8);
         Rect.setHeight(10);
         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();
      }
   }
}
卓越飞翔博客
上一篇: 在 C# 中,如何在不使用 foreach 的情况下将项目从一个列表复制到另一个列表?
下一篇: 在C/C++中的Power函数
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏