2016-04-23 76 views
-3

有没有人知道,为什么这个下划线(错误)在说“股票是西装”的部分套装(儿童类股票)?C#父类和子类 - 从父类中挑选孩子

//Picking Suit out of the Stock 
     public System.Collections.ArrayList Suit() 
     { 
      System.Collections.ArrayList array = new System.Collections.ArrayList(); //looping through Persons array 
      foreach (Stock stock in allStock)//using code snippets 
      { 
       if (stock is Suit) //if it is a customer, display value, if not, return to the array list 
       { 
        array.Add(stock); 
       } 
      } 
      return array; 
     } 
+2

什么是错误它显示? – Shaharyar

+1

你为什么使用'ArrayList'?这是2002年。现在有更好的收藏 - 尝试'列表'。 – Enigmativity

回答

1

你的方法具有相同的名称作为您的子类:Suit。这是错误。

这个方法应该被重新命名(并可以使用LINQ进行重构)是这样的:

public List<Suit> GetSuits() 
{ 
    return 
     allStock 
      .Select(stock => stock as Suit) 
      .Where(suit => suit != null) 
      .ToList(); 
} 

或者不LINQ:

public List<Suit> GetSuits() 
{ 
    var result = new List<Suit>(); 

    foreach (Stock stock in allStock) 
    { 
     var suit = stock as Suit; 
     if (suit != null) 
     { 
      result.Add(suit); 
     } 
    } 

    return result; 
}