我有繼承這種方式訪問子類物業
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;
}
'((PartsCar)mainObject).WheelRadius'應該工作。但是,如果您必須將對象轉換爲子類型,則應該嘗試重新設計它。 –
順便說一下,你應該在'PartsParent'中定義'Price',因爲你所有的孩子類型都需要一個價格。如果是這樣,你可以在不轉換的情況下訪問'mainObject.Price'。 –
@ J.C是的,你是正確的,共同的屬性應該只是父類的一部分,並且所討論的對象屬性只是一個樣本。你的建議解決了我的問題 –