C#列表< T>内部 [英] C# List<T> internals

查看:82
本文介绍了C#列表< T>内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么,如列表中添加一个对象集合时究竟发生

What exactly happens when adding an object to a collection such as List?

List<Person> people = new List<Person>();
Person dan = new Person() { Name="daniel", Age=10 };
people.Add(dan);
dan = new Person() { Name = "hw", Age = 44 };

当我执行上面的代码中,列表<人>人没有得到通过最后一行的影响。
所以我假设列表的拷贝的的的引用的添加对象,所以改变基准时,列表不会被影响。我是正确的?

When I execute the above code, the List<Person> peopledoes not get affected by final line. So I am assuming that the list copies the references of the added object, so when change the reference, the list does not get affected. am I correct?

推荐答案

好吧,你已经证明实际上并不向列表中添加任何东西的代码。我假设你的意思有:

Well, the code you've shown doesn't actually add anything to the list at all. I assume you meant to have:

people.Add(dan);

在那里的地方?

但是,是的中,列表< T> 包含对象的引用。它不知道在哪里的引用都从何而来。这是值得被明确一个变量,它的值之间的差异。当你调用:

But yes, the List<T> contains references to objects. It doesn't know about where the references have come from. It's worth being clear about the difference between a variable and its value. When you call:

people.Add(dan);

这副本参数表达式的值(),在这种情况下,作为参数在列表与LT的初始值; T>。新增。这个值只是一个参考 - 它具有与变量没有关联,除了它碰巧是当时的变量值时,清单< T>。新增被称为

that copies the value of the argument expression (dan) in this case as the initial value of the parameter within List<T>.Add. That value is just a reference - it has no association with the dan variable, other than it happened to be the value of the variable at the time when List<T>.Add was called.

这是完全一样的下列情况:

It's exactly the same as the following situation:

Person p1 = new Person { Name = "Jon" };
p2 = p1;
p1 = new Person { Name = "Dan" };

下面,值 P2 仍然会是名为乔恩的人一个参考 - 第二行只是 P1 的值复制到 P2 而不是两个变量一起关联。一旦你理解了这一点,你可以使用同样的逻辑方法的参数。

Here, the value of p2 will still be a reference to the person with the name "Jon" - the second line just copies the value of p1 to p2 rather than associating the two variables together. Once you understand this, you can apply the same logic to method arguments.

这篇关于C#列表&LT; T&GT;内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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