简体   繁体   中英

After loop all elements same

I want to assign value to elements of my array. after running this, all elements of ListResults are same as last element of ListROI.

ListResults = new DataPoint[nROIrow];
DataPoint TempRes = new DataPoint();
System.Collections.ArrayList List = new System.Collections.ArrayList();

for (int i = 0; i < nROIrow; i++)
{
   TempRes.X = ListROI[i].X;
   TempRes.Y = ListROI[i].Y;
   TempRes.u = dispROIcorr[i, 0];
   TempRes.v = dispROIcorr[i, 1];

   ListResults[i] = TempRes;

   disp.Xpix = ListResults[i].X;
   disp.Ypix = ListResults[i].Y;
   disp.X = ListResults[i].X;
   disp.Y = ListResults[i].Y;
   disp.U = ListResults[i].u;
   disp.V = ListResults[i].v;

   List.Add(disp);
   bSAVE.Enabled = true;  
}

You only create a new DataPoint(); one time. So you end up with an array full of references to that same single instance.

The simple fix:

ListResults = new DataPoint[nROIrow];
//DataPoint TempRes = new DataPoint();
System.Collections.ArrayList List = new System.Collections.ArrayList();

for (int i = 0; i < nROIrow; i++)
{
   DataPoint TempRes = new DataPoint();
   ...

   ListResults[i] = TempRes;

   var disp = new ...
   disp.Xpix = ListResults[i].X;
   ....

   List.Add(disp);
}  

The problem with your code is that you are reusing the TempRes variable. When you perform the "List.Add" you are just adding a reference to it, and all these references are (obviously) the same. You also modify it, so each identical reference logically points to the same identical data.

Instead, write:

System.Collections.ArrayList List = new System.Collections.ArrayList();

for (int i = 0; i < nROIrow; i++)
   {
     DataPoint TempRes = new DataPoint();
     ...

Note also that ArrayList is generally considered to be deprecated since .NET 2.0 and you should be using List<T> instead.

do

disp = new ... // whatever

before assigning values to disp[i].???

actually what is happening is all the references in your List are referring to disp which is the single object that was created outside the for loop, hence all items in List are pointing to same disp object, hence same values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM