C# 和多重继承


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

下面是 Shape 类中的 PaintCost 接口 −

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

shape 是基础类,而 Rectangle 是派生类 −

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();
      }
   }
}

更新于:2020-6-19

5K+ 查看

开启你的职业生涯 生涯

完成课程获得认证

开始入门
广告
© . All rights reserved.