C#值和引用类型 [英] C# Value and Reference types
问题描述
请参见下面提到的以下代码行:
Please see the following lines of code mentioned below:
byte[] a = { 1, 2, 3, 4 };
byte[] b = a; // b will have all values of a.
a = null;
在C#中,byte[]
是引用类型.现在,如果第3行中的a = null
,那么为什么b
由于其引用类型而不为null.如果我们选中b
,它将仍然具有所有a
值.
In C# byte[]
is a reference type. Now if a = null
in line 3, then why b
is not null since its a reference type. If we check b
it will still have all values of a
.
推荐答案
正如您所说,byte[]
是与所有其他数组一样的引用类型.让我们逐行分析样本;
As you said, byte[]
is a reference type like all other arrays. Let's analyze your sample line by line;
byte[] a = { 1, 2, 3, 4 };
->您在内存中创建了一个字节数组,并且a
是对该数组的引用.
--> You created a byte array in memory and a
is a reference that array.
byte[] b = a;
->您的b
所引用的对象与a
是{ 1, 2, 3, 4 }
,但它们是不同的引用.
--> Your b
is referencing the same object with a
which is { 1, 2, 3, 4 }
but they are different references.
a = null;
->您的a
没有引用内存中的任何位置,但这不会影响b
.
--> Your a
is not referencing anywhere in the memory but that doesn't effect b
.
这篇关于C#值和引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!