gpt4 book ai didi

c# - 为什么对通用列表的显式转换不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:45 24 4
gpt4 key购买 nike

我正尝试在构造函数中为派生类 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 .

关于c# - 为什么对通用列表的显式转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9891400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com