2014-09-30 173 views
2

這是我目前的類型層次:調用的泛型類型從抽象父類List的方法

enter image description here

我想實現在PlaneRegion的方法,將調用一個在名爲Shift()方法列出它的派生類在列表中所有的人都稱爲PlaneBoundaries但他們是不同類型的

像這樣的:

public abstract class PlaneRegion<T> 
{ 
    public abstract List<T> PlaneBoundaries { get; set; } 
} 


public class Polygon : PlaneRegion<LineSegment> 
{ 
    public override List<LineSegment> PlaneBoundaries 
    { 
     get { return _planeBoundaries; } 
     set { _planeBoundaries = value; } 
    } 
    protected List<LineSegment> _planeBoundaries; 
} 


public class NonPolygon : PlaneRegion<IEdge> 
{ 
    public override List<IEdge> PlaneBoundaries 
    { 
     get { return _planeBoundaries; } 
     set { _planeBoundaries = value; } 
    } 
    private List<IEdge> _planeBoundaries; 

} 

理想情況下,它也應該返回對象的副本作爲其子類,而不是修改原始對象。

目前,我有接口IEdge由兩個類實現:線段和圓弧。我使用泛型的抽象超PlaneRegion因爲兩個繼承類,多邊形和NonPolygon,都有planeBoundaries,而是一個多邊形只包含直線(lineSegments),而NonPolygon可以直線或曲線(線段或圓弧),所以我實現像這個問題,你可以在下面的代碼片段,請參閱:Override a Property with a Derived Type and Same Name C#

然而,由於PlaneRegion和PlaneBoundaries在PlaneRegion是一個泛型類型它會導致問題,當我試圖呼籲PlaneBoundaries轉變。下面是移是如何目前實施的例子:

//In PlaneRegion 
public PlaneRegion<T> Shift(Shift inShift) 
{ 
    //does not work because Shift isn't defined for type T 
    this.PlaneBoundaries.Shift(passedShift); 
} 

//in Polygon 
public override Polygon Shift(Shift passedShift) 
{ 
    return new Polygon(this.PlaneBoundaries.Shift(passedShift)); 
} 

//In NonPolygon 
public override NonPolygon Shift(Shift passedShift) 
{ 
    return new NonPolygon(this.PlaneBoundaries.Shift(passedShift)); 
} 

有沒有辦法來調用一個泛型列表轉變這樣或T的可能性限制在編譯時實施IEdge類?我曾嘗試將PlaneRegion中的Shift設置爲通用,但它也不起作用。

此外,理想情況下,我希望它將原始對象的副本作爲子對象返回,並在這些對象上修改PlaneBoundaries而不是原始對象PlaneBoundaries,但不要這樣做。

+2

您是否試過限制泛型方法? '公共PlaneRegion (移inShift)其中T:IEdge' – 2014-09-30 18:58:44

+0

我想'IEdge'有一個'Shift'方法,你應該在'PlanBoundaries'每個項目,而不是名單本身上調用。如果是這樣的話@YuvalItzchakov對於如何處理它是正確的,這樣你就不需要重寫'Polygon'和'NonPolygon'類中的'Shift'。 – juharr 2014-09-30 19:07:47

回答

1

您可以縮小PlaneRegion類承認IEdge接口的唯一實現在T:

public abstract class PlaneRegion<T> where T : IEdge 
{ 
    public abstract List<T> PlaneBoundaries { get; set; } 
} 

此外,在Shift功能,您可能希望將其應用到每一個項目列表,而不是整個列表,所以你應該將其更改爲:

//In PlaneRegion 
public PlaneRegion<T> Shift(Shift inShift) 
{ 
    this.PlaneBoundaries.ForEach(x => x.Shift(passedShift)); 
}