C# 和多重繼承
C# 不支援多重繼承。要實現多重繼承,請使用介面。
這是在 Shape 類中的 PaintCost 介面 −
public interface PaintCost {
int getCost(int area);
}形狀是我們的基類,而 Rectangle 是派生類 −
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();
}
}
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP