当列表的新内容未在循环中声明时,列表将反转;It’’’’我要填满它们.为什么?

本文关键字:列表 It 我要 为什么 满它们 新内容 循环 声明 | 更新日期: 2023-09-27 18:23:55

这是一个"为什么"的问题,而不是"如何"的问题。我正在用C#编写一个小的ArcGIS项目,我必须构建两个列表来做一些稍后的工作。这是代码:

List<double[]> store_coords = new List<double[]>();
List<IPoint> store_points = new List<IPoint>();
double[] templist = new double[2];
IPoint newpoint = new PointClass();
IFeature feature = null;
while ((feature = buildingCursor.NextFeature()) != null)
{
    IPolygon gon = (IPolygon)feature.Shape;
    templist[0] = gon.FromPoint.X;
    templist[1] = gon.FromPoint.Y;
    store_coords.Add(templist);
    newpoint.X = gon.FromPoint.X;
    newpoint.Y = gon.FromPoint.Y;
    store_points.Add(newpoint);
}

现在,在此之后,store_coords和store_points列表将完全向后。就好像Add方法将templist和newpoint放在Lists的开头而不是结尾。

然而,当我添加时

templist = new double[2];

newpoint = new PointClass();

到while循环的开头,列表不再反转。

这是怎么回事?o_o

当列表的新内容未在循环中声明时,列表将反转;It’’’’我要填满它们.为什么?

以下是代码的作用:

List<double[]> store_coords = new List<double[]>();
List<IPoint> store_points = new List<IPoint>();
//Allocates a new double[] object in memory say TM1
double[] templist = new double[2];
//Allocates a new PointClass object in memory say PM1
IPoint newpoint = new PointClass();
IFeature feature = null;
//first loop
feature = buildingCursor.NextFeature())
IPolygon gon = (IPolygon)feature.Shape;
//double is a value type so the X and Y are being copied into T[1] and T[2]
templist[0] = gon.FromPoint.X;
templist[1] = gon.FromPoint.Y;

//adds a reference to Temp list to the list (a reference to memory location TM1)
store_coords.Add(templist);
//double is a value type so the X and Y are being copied into newpoint.X and newpoint.Y
newpoint.X = gon.FromPoint.X;
newpoint.Y = gon.FromPoint.Y;
//adds a reference to NewPoint object to the list (a reference to memory location TM2)
store_points.Add(newpoint);
//second loop
feature = buildingCursor.NextFeature()) != null
IPolygon gon = (IPolygon)feature.Shape;
//double is a value type so the X and Y are being copied into T[1] and T[2]
//this is updating double[] referenced by templist at TM1, so it is updating the
//array at TM1 that is being referenced by the List store_coords
//if you look at store_coords after these two calls you will see store_coords will have the new values already
templist[0] = gon.FromPoint.X;
templist[1] = gon.FromPoint.Y;

//adds a reference to Temp list to the list (a reference to memory location TM1)
//this should be adding the same object to the list so the list will have two references to
//the array stored at memory location TM1
// at this point store_coords not only has two cords with the same value it has two arrays
// that have the same value and are the same object in memory, so store_coords[0] == store_coords[1]
store_coords.Add(templist);