C#中:当在同一对象两个List<对象>的变量,是在这个过程中复制的对象? [英] C#: When adding the same object to two List<object> variables, is the object cloned in the process?

查看:233
本文介绍了C#中:当在同一对象两个List<对象>的变量,是在这个过程中复制的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似这样:

// Declarations:
List<SomeType> list1 = new List<SomeType>();
List<SomeType> list2 = new List<SomeType>();

...

SomeType something = new SomeType("SomeName");
list1.Add(something);
list2.Add(something);

...

list1[indexOfSomething] = new SomeType("SomeOtherName");

和在list2中的对象没有改变...是预期的结果?

And the object in list2 isn't changed... Is that the expected result?

推荐答案

是的,但什么也没有克隆。在分配之前,相同的对象是在这两个列表。 。分配后,必须在两个列表中两个独特的对象

Yes, but nothing's cloned. Before the assignment, the same object is in both lists. After the assignment, you have two unique objects in two lists.

做到这一点:

list1[indexOfSomething].name = "SomeOtherName";



列表2 的对象会发生变化,了。

and the object in list2 will change, too.

这篇关于C#中:当在同一对象两个List&LT;对象&gt;的变量,是在这个过程中复制的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆