c# - C#中的数组是引用类型,为什么它们充当值类型?

标签 c# .net arrays c#-4.0

根据 MSDN,如果所有数组都是引用类型,那么为什么在给定的示例代码中,t2 的新值没有反射(reflect) t1 的变化?

string[] data = new[] { "One", "Two" };

var t1 = data[0];

Console.WriteLine(t1);

var t2 = t1;
t2 = "Three"; //assigning the new value, and this should reflect in t1

Console.WriteLine(t2);
Console.WriteLine(t1); // this should print 'Three', but it prints 'One'

Console.Read();

enter image description here

http://msdn.microsoft.com/en-us/magazine/cc301755.aspx

Arrays are mechanisms that allow you to treat several items as a single collection. The Microsoft® .NET Common Language Runtime (CLR) supports single-dimensional arrays, multidimensional arrays, and jagged arrays (arrays of arrays). All array types are implicitly derived from System.Array, which itself is derived from System.Object. This means that all arrays are always reference types which are allocated on the managed heap, and your app's variable contains a reference to the array and not the array itself.

最佳答案

一张图片胜过一千个字,所以这里是发生了什么:

Before and After

“三”赋值给t2的效果是赋值前t1t2引用了同一个对象,但在赋值后它们引用了不同的对象。这里没有其他事情发生。

如果你有一个可变对象数组,并且操纵它们的值而不是设置它们的引用,情况就会不同。例如,假设用 StringBuilder 对象数组替换字符串数组,并调用 t2.Replace("Two", "Three") 而不是赋值。现在效果会有所不同,因为 t1t2data[0] 将指向同一个对象。

关于c# - C#中的数组是引用类型,为什么它们充当值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29032237/

相关文章:

c# - NodaTime TypeInitializationException 仅限设备,仅限发布

php - 从xml文件中检索后,将数据插入不同行的mysql php

java - 不想在最后打印逗号

c# - 如何将表达式 Func<T,int> 转换为 Func<T,object>

c# - 来自以编程方式多次添加的用户控件的访问控件?

.net - 是什么触发了第二代垃圾回收?

c# - FileShare.None 是否使线程等待文件流关闭?

c# - 我可以选择在运行时关闭 JsonIgnore 属性吗?

java - 如何使用 Jersey 发布字符串数组

c# - 如何将自动增量创建的一个表中的主键插入到第二个表中作为外键?