
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();
}
}
}以上就是C# 和多重继承的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号