我有继承这种方式访问子类物业
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是的,你是正确的,共同的属性应该只是父类的一部分,并且所讨论的对象属性只是一个样本。你的建议解决了我的问题 –