将对象的引用添加到列表中
我有以下代码:
Point a = new Point(3, 3);
List<Point> points = new List<Point>();
points.Add(a);
a = new Point(50,50);
a.X += 50;
但是假设我希望最后两行代码也影响列表中的值;我该怎么做呢? 我的猜测是添加指向列表的指针?但我认为即使如此“new Point(50,50);”仍然不会更新列表的值吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你不需要指针。对 .NET 世界中的对象的引用可以被认为本质上等同于非托管代码世界中的指针。当您添加同时存在 值类型和引用类型这一事实时,事情会变得有点棘手,但在这种情况下,直接在数组中修改对象或对象的引用就足够了。
因此,您可以执行以下任一操作:
或者
(尽管您应该可能养成这个习惯 将结构视为不可变的,因此请考虑上述内容仅用于示例目的)。
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:
or
(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: