ToList()——它是否创建了一个新列表? [英] ToList()-- does it create a new list?

查看:26
本文介绍了ToList()——它是否创建了一个新列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堂课

public class MyObject
{
   public int SimpleInt{get;set;}
}

我有一个 List,我 ToList() 它然后改变 SimpleInt 之一,我会改变传播回原始列表.换句话说,以下方法的输出是什么?

And I have a List<MyObject>, and I ToList() it and then change one of the SimpleInt, will my change be propagated back to the original list. In other words, what would be the output of the following method?

public void RunChangeList()
{
  var objs = new List<MyObject>(){new MyObject(){SimpleInt=0}};
  var whatInt = ChangeToList(objs );
}
public int ChangeToList(List<MyObject> objects)
{
  var objectList = objects.ToList();
  objectList[0].SimpleInt=5;
  return objects[0].SimpleInt;

}

为什么?

P/S:如果发现很明显,我很抱歉.但是我现在没有编译器...

P/S: I'm sorry if it seems obvious to find out. But I don't have compiler with me now...

推荐答案

是的,ToList 将创建一个新列表,但因为在这种情况下 MyObject 是一个引用类型那么新列表将包含对与原始列表相同对象的引用.

Yes, ToList will create a new list, but because in this case MyObject is a reference type then the new list will contain references to the same objects as the original list.

更新新列表中引用的对象的 SimpleInt 属性也会影响原始列表中的等效对象.

Updating the SimpleInt property of an object referenced in the new list will also affect the equivalent object in the original list.

(如果 MyObject 被声明为 struct 而不是 class 那么新列表将包含原始列表中元素的副本,并且更新新列表中元素的属性不会影响原始列表中的等效元素.)

(If MyObject was declared as a struct rather than a class then the new list would contain copies of the elements in the original list, and updating a property of an element in the new list would not affect the equivalent element in the original list.)

这篇关于ToList()——它是否创建了一个新列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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