2015-01-05 59 views
2

我寫這個代碼(僅第一行是重要):創建方法與通用參數

public void InsertIntoBaseElemList(ref List<XElem> List, XElem Element) 
{ 
    for (int index = 0; index < List.Count; index++) { 
     if (List[index].Position < Element.Position && index + 1 == List.Count) { 
      List.Add(Element); 
     } else if (List[index].Position > Element.Position) { 
      List.Insert(index, Element); 
     } 
    } 
} 

此方法基本上插入XElem類型的元素到XElem類型的列表。
(在這種情況下,兩個參數必須具有相同的類型,XElem

我有這些列表的多個,但它們不具有相同的類型。
爲了允許將YElem類型的元素插入YElem類型的列表中,我必須複製此方法並更改參數類型。

是否有可能編寫一個可以處理多個類型作爲參數的單一方法,至此參數1和參數2是相同類型的?
我讀到泛型類型,但我could'nt使其工作...

+0

基類不是泛型的,是正確的嗎? – im1dermike

+0

他在問一個通用的解決方案 – Jonesopolis

+3

作爲一個附註,你在那裏的'ref'似乎毫無意義。 – Chris

回答

1

試試這個:

public void InsertIntoBaseElemList<T>(ref List<T> List, T Element) 
where T : BaseElem 

假設XElem和YElem從BaseElem

+0

就是這樣!非常感謝你!我會在5分鐘內接受... –

+0

爲什麼我被downvoted? –

+0

你走了。我沒有downvote btw –

4

假設類型實現相同的接口或基類,你可以做到以下幾點:

public void InsertIntoBaseElemList<TElem>(ref List<TElem> List, TElem Element) where TElem : IElem { 
    for (int index = 0; index < List.Count; index++) { 
     if (List[index].Position < Element.Position && index + 1 == List.Count) { 
      List.Add(Element); 
     } else if (List[index].Position > Element.Position) { 
      List.Insert(index, Element); 
     } 
    } 
} 

where子句限制可以指定爲參數的類型,並允許您訪問該方法中該類型的屬性&。

2

繼承你想要的東西,像下面這樣:

public void InsertIntoBaseElemList<T>(List<T> List, T Element) where T : IElem 
{ 
    for (int index = 0; index < List.Count; index++) 
    { 
     if (List[index].Position < Element.Position && index + 1 == List.Count) 
      List.Add(Element); 
     else if (List[index].Position > Element.Position) 
      List.Insert(index, Element); 
    } 
} 

使用IElem作爲定義Position接口和XElem實施和YElem
如果Position被定義在一個公共的基類中,你也可以使用它,例如, where T : BaseElem

ref參數不需要,因爲List<T>是參考類型。

根據你的解釋如下可能是一種替代方法,您的問題,這是比較容易理解/ IMO維護:

public void InsertIntoBaseElemList<T>(List<T> List, T Element) where T : BaseElem 
{ 
    var index = List.FindIndex(i => i.Position > Element.Position); 
    if (index < 0) // no item found 
     List.Add(Element); 
    else 
     List.Insert(index, Element); 
} 
+0

@ChrFin有大約10個像準備,準備好,完成,失敗的列表。這些列表中的所有元素必須具有特定的順序。這是代表位置。將一個元素從一個列表移動到另一個列表時,我無法將其添加到新列表的末尾,這會破壞列表中的順序。我必須根據其他元素在新列表中找到正確的位置,並在其中插入它。 –

+0

@NoelWidmer:現在我明白了,請看看我的替代方法,你是否也更喜歡它...... – ChrFin

1

假設XElem是用戶創建的類,你可以先創建一個稱爲IElem的接口,它包含XElem和YElem的常用屬性(如Position)。然後使XElem和YElem實現您創建的接口,並在方法的簽名上使用接口而不是具體的類。示例如下:

public interface IElem 
{ 
    int Position {get; set; } 
} 

public class XElem : IElem ... 

public void InsertIntoBaseElemList(ref List<IElem> List, IElem Element)