Method返回一个ParentClass对象,该对象可以是两个ChildClass类型之一。如何公开ChildClass属性?

时间:2017-01-11 00:55:24

标签: c# list inheritance parent-child

根据下面的代码,我有一个GetOrderPreviewSecurity()方法,它返回一个Security,它是Stock和MutualFund的父类。

GetOrderPreviewSecurity()方法实际上只向Stock属性返回Stock类型或MutualFund类型。我遇到的问题是尝试访问特定于子级的属性,如下面的评论中所述。

有没有办法可以强制演员或清理它比#34; var newThing =(ChildClass)SecurityClass更清洁;"并使用newThing?

public class Stock : Security
{
   public string Ask;
   public string Bid;
}

public class MutualFund : Security
{
   public string AssetClass;
   public string Category;
}

public Security PreviewSecurity;

  public Security GetOrderPreviewSecurity(_orderTickerText){
     //Do stuff
     if (boolean thing)
        return new Stock();
     else if (boolean thing)
        return new MutualFund();
     else
        return new Security("empty");
  }

//Some stuff

        private void ExecutePreviewOrder()
        {            
            if (!string.IsNullOrEmpty(_orderTickerText) && _orderShareQuantity > 0)
            {   
                //Returns a **Security**
                PreviewSecurity = _portfolioService.GetOrderPreviewSecurity(_orderTickerText);

                if (PreviewSecurity is Stock)
                {
                    //PreviewSecurity is still a Security type. 
                    //No Bid or Ask properties available
                    PreviewBid = PreviewSecurity.Bid; 
                    PreviewAsk = PreviewSecurity.Ask;

                }
                else if (PreviewSecurity is MutualFund)
                {
                    //PreviewSecurity is still a Security type.
                    //No AssetClass or Category propeties available 
                    PreviewAssetClass = PreviewSecurity.AssetClass;
                    PreviewCategory = PreviewSecurity.Category;
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

一旦您检查了类型,我认为没有任何问题可以退回安全保护。

if (PreviewSecurity is Stock)
{
    PreviewBid = (Stock)PreviewSecurity.Bid; 
    PreviewAsk = (Stock)PreviewSecurity.Ask;
}
else if (PreviewSecurity is MutualFund)
{
    PreviewAssetClass = (MutualFund)PreviewSecurity.AssetClass;
    PreviewCategory = (MutualFund)PreviewSecurity.Category;
}

答案 1 :(得分:1)

你需要围绕整个事物设置一组括号,如下所示:

if (PreviewSecurity is Stock)
{
    PreviewBid = ((Stock)PreviewSecurity).Bid;
    PreviewAsk = ((Stock)PreviewSecurity).Ask;
}
else if (PreviewSecurity is MutualFund)
{
    PreviewAssetClass = ((MutualFund)PreviewSecurity).AssetClass;
    PreviewCategory = ((MutualFund)PreviewSecurity).Category;
}

我认为问题是点的优先级高于强制转换运算符,因此首先应用点运算符,然后将转换运算符应用于点运算符返回的任何内容。