繁体   English   中英

如何转换为通用集合

[英]How to cast to generic collection

我有一个通用的集合路径,其中T是Segment-Segment是抽象类。 我有一个Path的派生类ClosedPath,其中包含从抽象基类Segment到中间类LineSegment的派生类SpecialLineSegments。 我试图选择满足条件的路径,然后对其进行修改,使其可能包含不同类型的细分,并且可能不再是ClosedPath。...所以我试图转换为Path。 编译器给出错误消息,提示无法进行强制转换。

       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
  }

LineSegment源自Segment

由于List<T>您无法从ClosedPathPath<LineSegment>ClosedPathPath<Segment> List<T>
例如:

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

如果要直接进行转换,则可能具有内部为ClosedPathPath<Segment> 这将导致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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM