我正尝试在构造函数中为派生类 IntersectionPath 转换对象列表,如下所示。
public class IntersectionPath : Path<IntersectionSegment>, IEnumerable
{
//Constructors
public IntersectionPath() : base() { Verts = null; }
public IntersectionPath(List<Intersection> inVerts, List<Segment<Node>> inEdges) : base()
{
this.Segments = (List<IntersectionSegment>) inEdges;
}
}
Segments 在通用基类 Path 中定义
public class Path<T> : IEnumerable<T> where T : Segment<Node>
{
//public properties
public List<Direction> Directions {get; set; }
public List<T> Segments { get; set; }
}
我已经在 IntersectionSegment 类中为转换定义了一个显式运算符(见下文,所以我不清楚为什么这不会编译。我在 IntersectionPath 构造函数中有一个关于转换的错误消息。
public class IntersectionSegment : Segment<Intersection>
{
//curves which intersect the primary curve at I0(Start Node) and I1(End Node)
public Curve C0 { get; set; }
public Curve C1 { get; set; }
public IntersectionSegment():base() {}
public IntersectionSegment(Intersection n0, Intersection n1):base(n0,n1){}
public static explicit operator IntersectionSegment(Segment<Node> s)
{
if ((s.Start is Intersection) && (s.End is Intersection))
{
return new IntersectionSegment(s.Start as Intersection,s.End as Intersection);
}
else return null;
}
public static explicit operator List<IntersectionSegment>(List<Segment<Node>> ls)
{
List<IntersectionSegment> lsout = new List<IntersectionSegment>();
foreach (Segment<Node> s in ls)
{
if ((s.Start is Intersection) && (s.End is Intersection))
{
lsout.Add(new IntersectionSegment(s.Start as Intersection,s.End as Intersection));
}
else return null;
}
return lsout;
}
段定义为:
public class Segment <T> : Shape where T : Node
{
//generic properties
public T Start { get; set; }
public T End { get; set; }
}
List<InteractionSegment>
与 InteractionSegment
不同.将一种类型的列表转换为另一种类型的列表不会转换每个项目。
你需要做这样的事情:
this.Segments = inEdges.Select(x => (InteractionSegment)x).ToList();
这使用 LINQ to Objects 来转换 inEdges
中的每个对象到InteractionSegment
对象并将结果放回列表中,然后分配给 this.Segments
.
我是一名优秀的程序员,十分优秀!