2013-11-15 55 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,其中包含适用于您的应用程序的正确属性。