2012-03-19 52 views
2

我有一个泛型集合路径,其中T是段 - 段是抽象类。 我有一个包含从抽象基类段经由中间类线段派生类SpecialLineSegments路径的派生类ClosedPath。 我想选择满足条件的路径,然后我将修改它,使得它可以包含不同类型段的,可能不是一个ClosedPath了....所以我试图转换为路径。编译器给出错误,表明这种转换是不可能的。如何转换为普通集合

 public static void Method1(ClosedPath[] paths) 
     { 
      bool condition = false; 
      //working code.. 

      Path<Segment> Pslct = new Path<Segment>(); 
      foreach (ClosedPath P in paths) 
      { 
       if (condition) 
       { 
        //working code 

        Pslct = (Path<Segment>) P; 

       } 

      } 
     } 

路径定义如下......

public class Path<T> : IEnumerable<T> where T : Segment 
{ 
    private List<T> segments = new List<T>(); 

    public List<T> Segments 
    { 
     set { segments = value;} 
     get { return this.segments; } 
    } 

    public T this[int pos] 
    { 
     get { return (T)segments[pos]; } 
     set { segments[pos] = value; } 
    } 

    public Path() 
    { 
     this.Segments = new List<T>(); 
    } 

    public Path(List<T> s) 
    { 
     this.Segments = s; 
    } 

    public void AddSegment(T s) {Segments.Add(s);} 

    public int Count {get {return Segments.Count;}} 

    IEnumerator<T> IEnumerable<T>.GetEnumerator() 
    { return Segments.GetEnumerator();} 
    IEnumerator IEnumerable.GetEnumerator() 
    { return Segments.GetEnumerator(); } 
} 

ClosedPath从

public class LinePath<T> : Path<T>, IEnumerable<T> where T : LineSegment 
    { 
     //working code 
    } 

线段源自段

+0

如何定义路径? – 2012-03-19 14:00:50

+0

@James上面编辑 – gwizardry 2012-03-19 14:10:04

+0

写一个显式的转换操作符。 – phoog 2012-03-19 14:10:34

回答

0

不能从ClosedPathPath<LineSegment>)转换为Path<Segment>派生是由于List<T>
例如:

List<Segment> foo = new List<LineSegment>(); //Will not compile 

如果您是直接转换,你可以有一个Path<Segment>这是一个内部ClosedPath。这将导致AddSegment(Segment s)失败,因为它会尝试添加Segment s到内部List<LineSegment>。因此,转换时必须投射内部列表。

if (condition) 
{ 
    //working code 

    // Convert the ClosedPath LineSegments to Sements to create the Path<Segment> 
    Pslct = new Path<Segment>(P.Cast<Segment>().ToList()); 

<OldAnswer>

假设ClosedPath : LinePath<LineSegment>你应该能够使用LINQ .Cast<>()

Path<Segment> Pslct = paths.Cast<Path<Segment>>(); 

</OldAnswer >

+0

是的。我没有LINQ经验....也许我应该快速阅读LINQ。 – gwizardry 2012-03-19 14:31:35

+0

看了更多一点--Cast将无法工作。编辑答案。 – David 2012-03-19 14:44:40

+0

显式转换解决方案可以编译,但在运行时测试之前还需要做其他一些事情。 – gwizardry 2012-03-19 14:47:49