开发者

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


You would access the value directly in the list:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜