按值传递 ref 参数并将其设置为 null

发布于 2024-11-09 06:15:39 字数 234 浏览 2 评论 0原文

考虑以下代码片段

Form form2 = new Form();

  test(form2);
  form2.Show();

public void test(Form f)
{
  f = null;
}

由于 f 还保存对 Form2 的“另一个”引用,因此将 f 设置为 null 也应该将 Form2 设置为 null,但事实并非如此。需要一个很好的解释才能理解这一点。

Consider the following code Snippet

Form form2 = new Form();

  test(form2);
  form2.Show();

public void test(Form f)
{
  f = null;
}

Since f also holds "another" reference to Form2, setting f to null should set Form2 to null as well, which it doesn't. Need a good explanation to understand this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我一直都在从未离去 2024-11-16 06:15:39

设置为 null 的引用是 form2 引用的本地副本。由于引用是按值传递的,这意味着制作精确的副本并传递副本,因此原始文件保持不变。

这里传递的值可以被视为内存地址(这与虚拟机的情况并不完全一样,但它是一个有用且充分的比喻)。

在测试方法中,您将保存该地址副本的变量设置为 null。这不会产生任何进一步的后果。

如果您使用存储在变量中的地址来访问和更改该地址所引用的实际对象,情况会非常不同。您正在此处更改实际内容,因此在局部变量超出范围后,所有更改仍然保留。

退后一步:

您可以将变量视为一张带有朋友(您的对象)地址的纸条。
如果你烧掉这张纸(将变量设置为空),你的朋友不会受到影响。
如果你使用论文访问该地址并给你的朋友送礼物或打他的脸(调用变量后面的对象上的方法),他肯定会受到影响,你必须承担后果

The reference set to null is the local copy of the form2 reference. As the reference is passed by value, meaning making an exact copy and passing the copy, the original remains untouched.

The value passed here can be seen as a memory address (which is not exactly the case vith VMs but it is a helpful and adequate metaphor).

In the test method, you set a variable holding a copy of this address to null. This has no further consequences whatsoever.

The case is very different if you use the address stored in the variable to access and change the actual Object the address refers to. You are changing the real thing here, so all changes remain after your local variable runs out of scope.

To take one more step back :

You can see the variable as a slip of paper with an address of a friend (your object).
If you burn the paper (setting the variable to null), your friend is not affected.
If you use the paper to visit the address and give your friend a present or slap him in the face (calling a method on the object behind the variable), he is definitely affected and you have to live with the consequences

叹梦 2024-11-16 06:15:39

(我假设这是 Java。)

方法参数始终按值传递。这意味着它们的内容总是被复制到新变量中。在这种情况下,变量 f 的内容(包含对对象的引用)将被复制到新变量。当新变量的内容被 null 替换时,原始变量的内容不受影响——它们仍然指向原始对象。

(I'm assuming this is Java.)

Method parameters are always passed by value. That means their contents are always copied to a new variable. In this case the contents of the variable f, which contains a reference to an object, are copied to a new variable. When that new variable's contents are replaced with null, the contents of the original variable are unaffected -- they still point to the original object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文