Re: [請益] 多型用在哪
本魯 OO 不太好
但你這例子多型嗎
這就只是子類別繼承父類別的屬性吧
多型比較像這樣吧
class DataLoader {
protected virtual string GetData() {
//..
}
public string Process() {
// ...
string data = GetData();
// ...
}
}
class NetworkLoader: DataLoader {
protected override string GetData() {
// get from network...
}
}
class FileLoader: DataLoader {
protected override string GetData() {
// get from file...
}
}
DataLoader loader = networkEnabled ? new NetowrkLoader() : new FileLoader();
string processedData = loader.Process();
讓子類別作他擅長的部份
父類別程式碼部分重用並且隱藏子類別的實作細節
函數只要能夠接受父類別的實體
所以使用父類別的函數也可以重用
要擴充只需要繼承父類別並且實作部分方法
※ 引述《empireisme (empireisme)》之銘言:
: 如題
: 看了stackoverflow的一個例子
: class Cup {
: int capacity
: }
: class TeaCup : Cup {
: string flavour
: }
: class CoffeeCup : Cup {
: string brand
: }
: Cup c = new CoffeeCup();
: public int measure(Cup c) {
: return c.capacity
: }
: 他的解釋是
: you can pass just a Cup instead of a specific instance. This aids in
: generality because you don't have to provide a specific measure() instance
: per each cup type
: 問題是我不是只要
: 在Cup 類別中定義 measure這個方法 不就可以了嗎
: 為何不要在宣告物件的時候都
: 使用
: CoffeeCup c= new CoffeeCup();
: 請問多型的用途是?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 50.35.84.213 (美國)
※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1614846627.A.236.html
推
03/04 17:35,
4年前
, 1F
03/04 17:35, 1F
→
03/04 18:06,
4年前
, 2F
03/04 18:06, 2F
推
03/04 18:09,
4年前
, 3F
03/04 18:09, 3F
→
03/04 18:09,
4年前
, 4F
03/04 18:09, 4F
推
03/04 18:26,
4年前
, 5F
03/04 18:26, 5F
→
03/04 18:26,
4年前
, 6F
03/04 18:26, 6F
推
03/04 18:38,
4年前
, 7F
03/04 18:38, 7F
推
03/04 19:29,
4年前
, 8F
03/04 19:29, 8F
推
03/04 19:46,
4年前
, 9F
03/04 19:46, 9F
推
03/04 21:17,
4年前
, 10F
03/04 21:17, 10F
→
03/04 21:18,
4年前
, 11F
03/04 21:18, 11F
推
03/04 23:37,
4年前
, 12F
03/04 23:37, 12F
推
03/05 01:11,
4年前
, 13F
03/05 01:11, 13F
推
03/05 02:00,
4年前
, 14F
03/05 02:00, 14F
推
03/05 02:52,
4年前
, 15F
03/05 02:52, 15F
推
03/05 11:53,
4年前
, 16F
03/05 11:53, 16F
→
03/05 12:31,
4年前
, 17F
03/05 12:31, 17F
→
03/05 12:32,
4年前
, 18F
03/05 12:32, 18F
→
03/05 12:55,
4年前
, 19F
03/05 12:55, 19F
→
03/05 13:02,
4年前
, 20F
03/05 13:02, 20F
→
03/07 00:24,
4年前
, 21F
03/07 00:24, 21F
→
03/07 14:35,
4年前
, 22F
03/07 14:35, 22F
推
03/09 04:45,
4年前
, 23F
03/09 04:45, 23F
討論串 (同標題文章)