2009-03-04 30 views
1

我有2個獨立的類:要使用哪種通用集合?

  • AreaProperties
  • FieldProperties

1 AreaProperties可以映射到1個FieldProperties。在不改變設計的情況下,我想要一種返回這些對象的List<>的方法

C#中的哪些泛型集合將適合?

我明白,我可以送2名列表和功能看起來像:

public List<AreaProperties> Save(ref List<FieldProperties>) 
{ 
    ..code 
} 

編輯: 德羅爾助手的解決方案聽起來不錯。不過,我最近發現FieldProperties和AreaProperties之間沒有1:1。 我現在將如何處理這個問題。我仍然想使用一個具有FieldProperties和AreaProperties對象的自定義類,但是如何處理1對多的場景?

+0

我不明白你想問什麼。你能澄清一些問題嗎? – 2009-03-04 18:56:16

+0

你所問的內容並不特別清楚,但你幾乎肯定不想通過引用來傳遞你的列表。請參閱http://pobox.com/~skeet/csharp/parameters.html – 2009-03-04 19:00:19

+0

請解釋代碼大綱/類結構的問題,這將有所幫助。 – NileshChauhan 2009-03-16 07:52:53

回答

9

您可以創建一個類/結構有兩個成員 - AreaProperties & FieldProperties並返回類列表

class Pair<T1, T2> 
{ 
    T1 t1; 
    T2 t2; 
} 

List<Pair<AreaProperties, FieldProperties>> Save(){ ...} 

或者使用System.Collections.Generic.KeyValuePair代替(按照下面帕特里克建議)

List<KeyValuePair<AreaProperties, FieldProperties>> Save(){ ... } 

這樣你也保持1..1的關係。

編輯: 如果你需要1..1關係,我想你想返回 列表>>代替這種方式,你有你的每個AreaProperties字段屬性的列表回來,你仍然保持關係它們之間。

+0

不應該是列表保存()? – 2009-03-04 20:24:58

3

你可以返回一個List<KeyValuePair<AreaProperties, FieldProperties>>

0

如果1:1間的關係需要被執行,我推薦的方法結構Dror mentioned。如果不執行1:1關係,我會考慮使用out參數修飾符。

void foo() 
{ 
    List<AreaProperties> listArea; 
    List<FieldProperties> listField; 
} 

void Bar(out List<AreaProperties> listArea, out List<FieldProperties> listField) 
{ 
    listArea = new List<AreaProperties>(); 
    listField = new List<FieldProperties>(); 

}