我有一个类和C'tor,但是由于某种原因它在每次迭代后都会删除“ polygonList ”。 通常它的读取行来自txt文件,其中包含ID号和ID的点数。 我必须说我的课程形式相似,才能完美。
任何提议我做错了什么?
calling from main class:
tempPoly = new Polygon(totalLine,pointsList);
班级
public class Polygon
{
public int polyID;
public List<Polygon> polygonList = new List<Polygon>();
public List<Point2D> vertexPoints = new List<Point2D>();
public List<Point2D> VertexPoints
{
get { return vertexPoints; }
set { vertexPoints = value; }
}
public Polygon(int polyID, List<Point2D> vertexPoints)
{
PolyID = polyID;
VertexPoints = vertexPoints;
}
public Polygon(string[] line, List<Point2D> points)
{
for (int k = 0; k < line.Length; k++)
{
foreach (var point in points)
{
if (line[k] == point.PntID)
{
VertexPoints.Add(point);
break;
}
}
}
polygonList.Add(new Polygon(int.Parse(line[0]), VertexPoints));
}
}
答案 0 :(得分:0)
如果totalLine
的类型为int,那么你永远不会调用在'polygonList'中添加项的构造函数的重载
答案 1 :(得分:0)
因为当你打电话给List<Polygon>
之一时,你正在制作一个新的 - 然后是空的 - Polygon
:
...
public List<Polygon> polygonList = new List<Polygon>();
public List<Point2D> vertexPoints = new List<Point2D>();
你可能想要的是一个静态列表,它只对Polygon
类的所有实例都存在一次。抛开并发问题,你可以这样做:
public static List<Polygon> polygonList = new List<Polygon>();
public static List<Point2D> vertexPoints = new List<Point2D>();
这样,Polygon的每个实例都会写入相同的列表。
答案 2 :(得分:0)
每次实例化新Polygon
时,列表都会被“删除”,因为polygonList
是Polygon
的字段。
polygonList.Add(new Polygon(int.Parse(line[0]), VertexPoints));
我希望有类似的东西:
public class Polygon
{
public int polyID;
public List<Point2D> vertexPoints = new List<Point2D>();
// etc
}
另一个负责维护Polygon
s列表的对象,例如:
public class Shape
{
public List<Polygon> Polygons { get; private set}
public Shape()
{
Polygons = = new List<Polygon>();
}
}
或者你可以使List静态只是为了使代码工作。这可能是一个设计缺陷。
public static List<Polygon> Polygons = new List<Polygon>();