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();
//打印对象的区域。
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}热门推荐
10 结婚婚庆祝福语简短
11 恭喜新郎父母简短祝福语
12 五十二新年祝福语简短
13 哥哥新婚祝福语创意简短
14 恩师退休花束祝福语简短
15 讲课祝福语简短10字
16 生日祝福语贺卡老师简短
17 老婆生日祝福语短句简短
18 简短有力的结婚祝福语