2010-03-22 53 views
3

我有2個列表:A類型和Aa類型之一。 AA型是由A型 所以繼承:公共屬性列表需要Concat 2繼承類型

List<A> listA = new List<A>(); 
List<Aa> listAa = new List<Aa>(); 

class Aa : A 

我:

public property Lists<A> 
{ 
    get 
    { 
    List<A> newList = new List<A>(); 
    //return concat of both lists 
    foreach(List l in listA) 
    { 
     newList.Add(l); 
    } 
    foreach(List l in listAa) 
    { 
     newList.Add(l); 
    } 
} 

我可以以某種方式使用,而不是foreach循環的毗連?即

get 
{ 
    return listA.Concat(listAa); 
} // this doesn't work 

其次,我該如何做屬性的設置部分?

set 
{ 
    //figure out the type of variable value and put into appropriate list? 
} 
+0

@Obalix:從原來的,我不是100%肯定這些都是通用的清單,而不是System.Collections.List .. – 2010-03-22 16:26:24

+0

@Reed Copsey:剛做格式化...... :-) ......根據Bernard的OP,列表被定義爲列表和列表。 – AxelEckenberger 2010-03-22 16:33:03

+0

啊,好吧 - 從原始文本中並不明顯,它包含:「List listA = new List();」等等,表明非泛型用法。 – 2010-03-22 16:50:53

回答

2

如果這些是通用的列表,像這樣:

List<A> listA; 
List<Aa> listAa; 

你應該能夠做到:

public IList<A> Lists 
{ 
    get 
    { 
     return listA.Concat(listB.Cast<A>()).ToList(); 
    } 
} 

Enumerable.Cast電話將允許你在List<Aa>轉換成IEnumerable<A>(因爲Aa是A的一個子類),這將使Concat工作。您可以通過撥打ToList()將其轉換回List<A>

至於屬性setter - 我不會建議使這個屬性包含一個屬性setter。這將以非常不規範的方式行事。相反,使用自定義方法處理設置列表最有可能是一個更好的主意。

如果你想在一個列表來傳遞,含AaA類,你可以使用類似:

public void SetLists(IEnumerable<A> newElements) 
{ 
    this.listA.Clear(); 
    this.listAa.Clear(); 
    foreach(A aElem in newElements) 
    { 
     Aa aaElem = aElem as Aa; 
     if (aaElem != null) 
      this.listAa.Add(aaElem); 
     else 
      this.listA.Add(aElem); 
    } 
} 

在這種情況下,做循環實際上是比試圖更有效使用LINQ來設置這些數組,因爲你將需要一些奇怪的過濾。

0

也,它會在.NET 4.0中工作,沒有一個造型,因爲協方差