Skip to main content
 首页 » 编程设计

c#之如何转换为通用集合

2024年01月02日29del

我有一个通用集合 Path,其中 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

请您参考如下方法:

你不能从 ClosedPath 转换( Path<LineSegment> ) 到 Path<Segment>是由于 List<T> .
例如:

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

如果您要直接转换,您可能会得到一个 Path<Segment>那是内部 ClosedPath .这会导致 AddSegment(Segment s)失败,因为它会尝试添加 Segment s到内部List<LineSegment> .因此,转换时必须强制转换内部List。

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

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

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