【发布时间】:2017-02-09 05:51:08
【问题描述】:
我有 2 个以这种方式继承的类
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; }
}
我有一个接受 PartsParent 类作为参数的函数,我如何在函数内将其转换为 partsCar / 作为 PartsBike 并访问 Price 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 是的,你是对的,公共属性应该只是 Parent 类的一部分,而有问题的对象属性只是一个示例。你的建议解决了我的问题
-
当然,这段代码应该可以工作。但是,我建议您考虑重新设计您的程序。就像@AymenDaoudi 的回答一样,将对象转换为子类型没有意义。
标签: c# linq class inheritance