了ToList() - 它创建一个新的列表? [英] ToList()-- Does it Create a New List?

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

问题描述

让我们说我有一个类

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

和我有一个列表<为MyObject> 和I 了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 被声明为结构而非那么新的列表将包含元素的副本,在原来的名单,并在新的列表更新元素的属性将的的影响原始列表相当于元素。)

(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天全站免登陆