2017-02-09 79 views
0

我有繼承這種方式訪問子類物業

public class PartsParent 
{ 

} 
public class PartsCar : PartsParent 
{ 
    public int WheelRadius { get; set; }  
    public int Price { get; set; } 
} 

public class PartsBike : PartsParent 
{ 

    public int Length { get; set; }  
    public int Weight { get; set; }  
    public int Price { get; set; } 
} 

2班,我已經接受了類PartsParent作爲參數,我怎麼能轉換這是partsCar /作爲PartsBike裏面的函數的函數和訪問屬性,如價格WheelRadius等?

private int PriceCollection(PartsParent mainObject) 
{ 

    int _price=0; 
    mainObject.OfType(PartsCar).Price;// something similar?? 
    return _price; 
} 
+0

'((PartsCar)mainObject).WheelRadius'應該工作。但是,如果您必須將對象轉換爲子類型,則應該嘗試重新設計它。 –

+2

順便說一下,你應該在'PartsParent'中定義'Price',因爲你所有的孩子類型都需要一個價格。如果是這樣,你可以在不轉換的情況下訪問'mainObject.Price'。 –

+0

@ J.C是的,你是正確的,共同的屬性應該只是父類的一部分,並且所討論的對象屬性只是一個樣本。你的建議解決了我的問題 –

回答

2

嗯,你正試圖將父類型轉換爲子類型,這是不可能的,爲什麼?

答案是,您試圖轉換爲子C1的父P可能實際上是C2類型的原始類型,因此該轉換將無效。

解釋這一點的最好辦法是,我這裏的某個地方閱讀計算器

你不能投哺乳動物爲狗一個短語 - 這可能是一隻貓。

你不能將食物投入三明治 - 它可能是一個芝士漢堡。

,你能做些什麼,雖然扭轉這種局面是這樣的:

(mainObject is PartsCar) ? (PartsCar)mainObject : mainObject 

即相當於:

mainObject as PartsCar 

然後訪問使用null coalescing operator(因爲mainObject的演員結果如果失敗,轉換結果將爲空,而不是拋出異常)。

您試圖使用的通用方法OfType<T>是一種擴展方法,可用於IEnumerable<T'>類型的對象,我認爲這不是您的情況。

1

繼承的想法是將超類中常見的東西組合起來,並將其他具體細節留給子類。所以如果一個屬性,比如Price,被排除在所有的子類之外,那麼它應該在超類中聲明。

但是,如果你仍然想使用這種方式,那麼你在尋找的是:

int _price = ((PartsCar)mainObject).Price; 

但是,如果有什麼對象是一些其他類的,說PartsGiftPartsParent繼承,但沒有價格?然後它會崩潰。

你幾乎真的需要檢查你的設計。

順便說一句,如果你想檢查一個對象是否真的是一個特定的類,那麼你可以使用is。

int number = 1; 
object numberObject = number; 
bool isValid = numberObject is int; // true 
isValid = numberObject is string; // false 
0

您可以使用關鍵字is檢查的類型和as關鍵字轉換爲目標兒童型如下。

if (mainObject is PartsCar) 
{ 
    var partscar = mainObject as PartsCar; 
    // Do logic related to car parts 
} 
else if (mainObject is PartsBike) 
{ 
    var partsbike = mainObject as PartsBike; 
    // Do logic related to bike parts. 
} 
0

如果你分開少見特性你的代碼塊這是可能的:

if (mainObject is PartsCar) 
{ 
    //Seprated code for PartsCar 
    // WheelRadius... 
    //Price... 
} 
else if (mainObject.GetType() == typeof(PartsBike)) 
{ 
    //Seprated code for PartsBike 
    //Length 
    //Weight 
    //Price 
}