C# 不支持多重继承

多重继承指的是一个类别可以同时从多于一个父类继承行为与特征的功能。与单一继承相对,单一继承指一个类别只可以继承自一个父类。
C# 不支持多重继承。但是,您可以使用接口来实现多重继承。下面的程序演示了这点:

同样使用:实现接口。

实例

  1. using System;
  2. namespace InheritanceApplication
  3. {
  4. class Shape
  5. {
  6. public void setWidth(int w)
  7. {
  8. width = w;
  9. }
  10. public void setHeight(int h)
  11. {
  12. height = h;
  13. }
  14. protected int width;
  15. protected int height;
  16. }
  17. // 基类 PaintCost
  18. public interface PaintCost
  19. {
  20. int getCost(int area);
  21. }
  22. // 派生类
  23. class Rectangle : Shape, PaintCost
  24. {
  25. public int getArea()
  26. {
  27. return (width * height);
  28. }
  29. public int getCost(int area)
  30. {
  31. return area * 70;
  32. }
  33. }
  34. class RectangleTester
  35. {
  36. static void Main(string[] args)
  37. {
  38. Rectangle Rect = new Rectangle();
  39. int area;
  40. Rect.setWidth(5);
  41. Rect.setHeight(7);
  42. area = Rect.getArea();
  43. // 打印对象的面积
  44. Console.WriteLine("总面积: {0}", Rect.getArea());
  45. Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));
  46. Console.ReadKey();
  47. }
  48. }
  49. }