原始值更改未反映在引用类型变量中(Original Values changes are not reflecting in reference types variable) object a = "1411"; object b = a; Console.WriteLine("Before Value of a " + a); Console.WriteLine("Before Value of b " + b); a = "5555"; Console.WriteLine("After Value of a " + a); Console.WriteLine("After Value of b " + b); Console.ReadKey();

输出:

之前的价值1411

之前的价值b 1411

之后的价值5555

在B 1411的价值之后

之后b的值也应改为5555吧? 因为b是引用类型变量。

object a = "1411"; object b = a; Console.WriteLine("Before Value of a " + a); Console.WriteLine("Before Value of b " + b); a = "5555"; Console.WriteLine("After Value of a " + a); Console.WriteLine("After Value of b " + b); Console.ReadKey();

output:

Before Value of a 1411

Before Value of b 1411

After Value of a 5555

After Value of b 1411

After Value of b also should changed to 5555 right? since b is reference types variable.

最满意答案

让我们一块一块地看一下这段代码,看看它的作用:

a = "1411";

这会将对象的引用存储到变量a 。 该对象是一个string ,并在堆上分配(因为它是一个引用类型)。

所以这里涉及两件事:

变量a 它引用的对象(字符串)

然后我们有这个:

b = a;

这将使变量b引用与引用相同的对象。

内部引用被实现为内存地址,因此如果(示例)字符串对象位于地址1234567890,则两个变量的值都将是该地址。

现在,你这样做:

a = "5555";

这将改变变量的内容,但b变量将保持不变。

这意味着b仍然引用旧对象,地址为1234567890,而a将引用不同的字符串对象。

你没有改变对象本身, a和b都指的是你改变a 。

正如马克在评论中所说,你可以把它比作在一张纸上给你一个房子的地址。 如果你给你的朋友一张纸,在第二张纸上写相同的地址,你指的是同一个房子。

但是,如果你给你的朋友一张带有不同地址的纸张,即使这两个房子看起来一样,它们也不是同一个房子

因此引用类型包含引用的变量之间存在很大差异。

Let's take this code piece by piece to see what it does:

a = "1411";

This will store a reference to an object into the variable a. The object is a string, and allocated on the heap (since it's a reference type).

So there are two pieces involved here:

The variable a The object (string) that it refers to

Then we have this:

b = a;

This will make the variable b reference the same object that a refers to.

References internally are implemented as memory addresses, and thus if (example) the string object lives at address 1234567890, then the values of the two variables would both be that address.

Now, then you do this:

a = "5555";

This will change the contents of the a variable, but the b variable will be left unchanged.

This means that b still refers to the old object, at address 1234567890, whereas a will refer to a different string object.

You did not change the object itself, that both a and b were referring to, you changed a.

As Marc said in a comment, you can liken this to giving you the address of a house on a piece of paper. If you give a piece of paper to your friend, writing up the same address on that second piece of paper, you are referring to the same house on both.

However, if you give your friend a paper with a different address on it, even if the two houses looks the same, they're not the same house.

So there's a big difference between reference type and variable containing a reference.

更多推荐