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# 和多重继承的详细内容。