【问题标题】:c# List been erased after each iterationc#列表在每次迭代后被删除
【发布时间】:2014-01-30 09:16:36
【问题描述】:

我有一个构建类和 C'tor,但由于某种原因,它会在每次迭代后删除“polygonList”。 通常它从包含 ID 号和点 ID 的 txt 文件中读取行。 必须说我有类似形式的课程,效果很好。

任何提供我做错了什么?

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));
    }
}  

【问题讨论】:

  • 那里为什么要休息?
  • @Robuust 如果找到匹配则停止迭代点-然后我们转到下一行
  • 每次迭代是什么意思?您只向多边形列表添加一个带有第一行的多边形,并且它没有任何迭代
  • 每次迭代=txt 文件中的新行。上面没有引用循环@SergeyBerezovskiy
  • @DimaB 不清楚你在问什么,以及引用的循环是什么。您不是在循环中将项目添加到 polygonList 。此外,完全不清楚您如何调用构造函数。变量名不足以理解您传递给构造函数的内容。

标签: c# list class constructor


【解决方案1】:

因为每当您调用 Polygons c'tors 之一时,您都会创建一个新的 - 然后是空的 - List&lt;Polygon&gt;

...
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 的每个实例都将写入 same 列表。

【讨论】:

    【解决方案2】:

    如果 totalLine 是 int 类型,那么您永远不会调用在 'polygonList' 中添加项目的构造函数的重载

    【讨论】:

      【解决方案3】:

      每次实例化一个新的Polygon 时,该列表都会被“擦除”,因为polygonListPolygon 的一个字段。

      polygonList.Add(new Polygon(int.Parse(line[0]), VertexPoints));
      

      我希望是这样的:

      public class Polygon
      {
          public int polyID;
          public List<Point2D> vertexPoints = new List<Point2D>();
          // etc
      }
      

      还有另一个负责维护Polygons 列表的对象,例如:

      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>();
      

      【讨论】:

        猜你喜欢
        • 2020-01-04
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 2012-09-19
        相关资源
        最近更新 更多