开发者

If I create a new List<T> from an existing list, are the members equal?

Assuming I have a List<Stuff> listA that has some items in it. I create a second list as follows:

List<Stuff> listB = new List<Stuff>(listA);

Let's say I have an item from listA, and I try to remove it from listB:

Stuff itemFromA = listA[0];
listB.Remove(itemFromA);

Assuming Stuff is a Class, should the item be successfully removed from listB? In other wor开发者_运维知识库ds, are the members the same objects or does the process of creating a new list clone the items?

I am experiencing behaviour in some code I'm debugging where the .Remove fails to remove the item from listB.


The List<T> Constructor (IEnumerable<T>) does not clone the items.

For value types the value is copied, for reference types a reference to the same object is added to the list.

List<object> listA = new List<object>();
listA.Add(new object());

List<object> listB = new List<object>(listA);
bool result = object.ReferenceEquals(listA[0], listB[0]);

// result == true
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜