【发布时间】:2012-04-11 02:15:48
【问题描述】:
我正在尝试在派生类 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; }
}
【问题讨论】:
-
您已经提供了 很多 代码 - 您可以尝试将其缩减为一个简短但完整的程序吗?
-
我意识到......我刚刚在以前的帖子中发现我被要求提供更多代码! :-s
-
如果您没有提供完整代码,通常会要求您提供更多信息,但简短而完整的代码通常没问题...
-
OK....我认为删除了一些内容以提高可读性。
标签: c# generics casting explicit-conversion