2013-11-15 54 views
0

我正在使用兩個不同的庫,每個庫都有自己的類型。這兩種類型都有x和y座標,而每種都有一些特殊的字段。我想將兩種類型(例如PointAPointB)都存儲在列表中。我不能使用基類,因爲PointAPointB是庫類型,不能修改。在列表中存儲不同的(不可修改的)類型

有這樣的事情,我不得不實際使用List內的列表(點數組數組)。我從庫調用的方法1返回List<PointA>,庫2的方法返回List<PointB>

在一個List中存儲這些點陣的最佳方式是什麼?使用List<List<Object>>並將返回數組中的每個對象轉換爲Object?看起來像這樣可以做得更優雅。

+0

'PointA'和'PointB'是否共享一個共同的'interface'或者base-type(除了'object')? –

+0

您是否考慮過使用適配器模式?每個適配器可以存儲其中一種類型的點,並且您將存儲點適配器的列表。 – Jonny

+0

你究竟在做什麼?即使它們具有共同的成員值,它們也不能以任何方式互換使用(除非這些庫以某種方式構建,例如使用反射或通用接口)。 – Mario

回答

1

我只能想到一種可能的解決方案。創建自己的「包裝」類處理類型統一/轉換(未經測試):

class StoredPoint { 
    PointA pa; 
    PointB pb; 

    public StoredPoint (PointA other) { 
     pa = other; 
     // pb is null 
    } 

    public StoredPoint (PointB other) { 
     pb = other; 
     // pa is null 
    } 

    public static implicit operator StoredPoint(PointA other) { 
     return new StoredPoint(other); 
    } 

    public static implicit operator StoredPoint(PointB other) { 
     return new StoredPoint(other); 
    } 

    public static implicit operator PointA(StoredPoint point) { 
     if (pa != null) 
      return pa; 
     return PointA(0,0); // some default value in case you can't return null 
    } 

    public static implicit operator PointA(StoredPoint point) { 
     if (pa != null) 
      return pa; 
     return PointA(0,0); // some default value in case you can't return null 
    } 

    public static implicit operator PointB(StoredPoint point) { 
     if (pb != null) 
      return pb; 
     return PointB(0,0); // some default value in case you can't return null 
    } 
    } 

然後,你可以只創建一個使用List<StoredPoint>列表,並添加這兩種類型的點吧。你是否能夠使用結果列表是一些不同的問題(主要是由於錯誤處理等)。

+0

這正是我需要的! –

+1

就像一個筆記。如果你不能混合類型,你可以使用'List ',另外存儲你是否有'PointA'或'PointB'並且輸入值。 – Mario

0

您可以使用System.Collections庫中的非通用ArrayList

但是更好的選擇可能是您創建自己的點類並將PointAPointB對象轉換爲它。

例如,假設你定義自己的類型PointList:

public class PointList : List<MegaPoint> 

(其中MegaPoint是你自己點的定義)。

因此,列表中的每一項都保證爲MegaPoint。然後,如果要添加其他類型的列表,實施方法,如:

public void AddFrom(List<PointA> points) 

public void AddFrom(List<PointB> points) 

不只是添加的項目,但它們轉換成你的「通用」 MegaPoint s。

現在,您的代碼可以根據需要使用這些庫,但是您的列表將始終包含一個類型,即MegaPoint,其中包含適用於您的應用程序的正確屬性。