如何转换为通用集合

时间:2012-03-19 13:58:07

标签: c# generics casting abstract-class

我有一个泛型集合Path,其中T是Segment - Segment是抽象类。 我有一个派生类的PathPath,它包含来自抽象基类Segment的派生类SpecialLineSegments,通过中间类LineSegment。 我正在尝试选择满足条件的路径,然后我将修改它,使其可能包含不同类型的段,并且可能不再是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派生自细分

1 个答案:

答案 0 :(得分: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());

<强>&LT; OldAnswer&GT;

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

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

<强>&LT; / OldAnswer&GT;