C# and multiple inheritance

WBOY
Release: 2023-09-02 21:29:02
forward
1207 people have browsed it

C# 和多重继承

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

这是类 Shape 中的接口 PaintCost -

public interface PaintCost {
   int getCost(int area);
}
Copy after login

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

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

现在让我们看看在 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();
      }
   }
}
Copy after login

The above is the detailed content of C# and multiple inheritance. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!