为list< T>一个指针?

为list< T>一个指针?

问题描述:

我注意到名单,LT的行为; T&GT; 不同的是从其他简单的对象,比如字符串的例。这个问题似乎新手,但真正让我吃惊,因为我认为列表&LT; T&GT; 很简单对象

I noticed that the behavior of List<T> is different from an other simple object, say String for example. The question can seem newbie but that really struck me cause I thought that List<T> were simple objects.

就拿下面的代码:

List<String> ls1 = new List<String>();
ls1.Add("a");
List<String> ls2 = ls1;
ls1.Add("b");



最后, LS1 将等于到 {A,b} 等会 LS2 。这是这个代码的行为确实不同:

At the end, ls1 will be equal to {"a", "b"} and so will ls2. This is really different from the behavior of this code:

String s1 = "a";
String s2 = s1;
s1 = "b";



其中, S1 是在最后等于 b S2 等于 A

Where s1 is at the end equal to b and s2 equal to a.

这意味着列表&LT; T&GT; 其实是一个指针权

That means that List<T> is in fact a pointer right?

列表&LT; T&GT; A的引用类型的,所以是的,它的行为就像一个指针

List<T> a reference type, so yes it behaves like a pointer.

字符串也是引用类型,但字符串是不可改变的,但它们却像的值类型在某些情况下,因此你的困惑在这里(参考类型的对比)

String is also a reference type, but strings are immutable and they behave like value types (contrast with reference types) in some cases hence your confusion here.

有就是为什么字符串工作的一个很好的解释这种方法在这里:的In C#,为什么字符串,其行为引用类型像值类型?

There is a good explanation of why string work this way here: In C#, why is String a reference type that behaves like a value type?