1

这是一个“为什么”的问题,而不是“如何”的问题。我正在用 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 放在列表的开头而不是结尾。

但是,当我添加

templist = new double[2];

newpoint = new PointClass();

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

这里发生了什么?o_O

4

1 回答 1

0

这是代码的作用:

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

...

于 2013-07-19T19:54:29.853 回答