2017-02-09 78 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 
}