加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#中的数组是引用类型,为什么它们作为值类型?

发布时间:2020-12-15 18:31:43 所属栏目:百科 来源:网络整理
导读:根据MSDN,如果所有数组都是引用类型,那么为什么在给定的示例代码中,t2的新值不能反映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 refl
根据MSDN,如果所有数组都是引用类型,那么为什么在给定的示例代码中,t2的新值不能反映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();

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.

解决方法

一张图片胜过千言万语,所以这是正在发生的事情:

赋值“3”到t2的效果是在赋值t1和t2引用相同对象之前,但在赋值之后它们引用不同的对象.这里没有其他任何事情发生.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读