다중 상속은 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();
}
}
}