简体   繁体   中英

Add references to objects to a list

I have the following code:

Point a = new Point(3, 3);

List<Point> points = new List<Point>();

points.Add(a);

a = new Point(50,50);

a.X += 50; 

But say I want the last two lines of code to also affect the value in the list; how would I go about doing this? My guess would be to add pointers to the list? But I think even then "new Point(50,50);" would still not update the list's value?

Thanks

No, you don't need pointers. A reference to an object in the .NET world can be thought of as essentially equivalent to a pointer in the world of unmanaged code. Things get a little tricker when you add in the fact that there are both value types and reference types , but in this case, modifying the object, or the object's reference, directly in the array is sufficient.

So, you can do either of the following:

points[0] = new Point(50, 50);

or

points[0].X = 50;
points[0].Y = 50;

(although you should probably get into the habit of treating structures as if they were immutable, so consider the above for example purposes only).

您可以直接在列表中访问该值:

points[0] = new Point(50, 50);

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