为什么只有使用 ref 关键字时才有效?

发布于 2024-12-02 17:44:36 字数 821 浏览 0 评论 0原文

我有这个容器类:

class Fruit
{
    public Apple apple;
    public Banana banana;
}

我在另一个类中有一个函数,如下所示:

public void ChangeFruit(Fruit fruit)
{
    fruit.apple = memberApple;
    fruit.banana = memberBanana;
}

效果很好。

但是,我想知道为什么这不起作用:

如果我将 ChangeFruit 方法更改为而不是获取容器,而是获取实际的水果类,如下所示:

public void ChangeFruit(Apple apple, Banana banana)
{
    apple = memberApple;
    banana = memberBanana;
}

那么这将不起作用,除非与每个参数一起传递 ref 关键字。为什么这里需要 ref 关键字而不是那里?

顺便说一句,当调用后一个 ChangeFruit 时,我这样称呼它:

ChangeFruit(myFruit.apple, myFruit.banana);

ChangeFruit(myFruit); 相反,

我只是想知道在传递容器类时我不需要 ref 关键字,但是当我单独传递每个水果时,我都会这么做。无论哪种方式,我都会传递 myFruit,除了在后一个示例中,我只是单独传递其成员变量而不是整个容器。

I have this container class:

class Fruit
{
    public Apple apple;
    public Banana banana;
}

And I have a function in another class that looks like this:

public void ChangeFruit(Fruit fruit)
{
    fruit.apple = memberApple;
    fruit.banana = memberBanana;
}

And that works fine.

However, I want to know why this doesn't work:

If I change the ChangeFruit method to instead of taking the container, to take the actual fruit classes, like this:

public void ChangeFruit(Apple apple, Banana banana)
{
    apple = memberApple;
    banana = memberBanana;
}

Then this does not work unless the ref keyword is passed with each argument. Why do I need the ref keyword here and not there?

By the way, when calling the latter ChangeFruit, I call it like this:

ChangeFruit(myFruit.apple, myFruit.banana);

As opposed to ChangeFruit(myFruit);

I just want to know when passing the container class I don't need the ref keyword but when I pass each fruit individually I do. Either way I am passing myFruit, except in the latter example I just pass its member variables individually instead of the entire container.

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

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

发布评论

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

评论(1

花开浅夏 2024-12-09 17:44:36

当您调用 ChangeFruit(myFruit.apple, myFruit.banana); 时,您正在传递 Fruit 类中这些属性的引用的副本。只有那些副本会在您的函数中被修改。事实上,您正在做的是对您的副本添加一个新引用,而这不会修改您的原始对象。

当您使用 ref 关键字时,您将传递对这些类型的引用,而不是副本

,但是当您调用 ChangeFruit(myFruit); 时。您正在传递容器引用的副本。它指向堆上的同一对象。并且您正在修改其中的内容。

when you are calling ChangeFruit(myFruit.apple, myFruit.banana); you are passing copies of the references of the these properties in the Fruit class. Only those copies are getting modified in your function.In fact what you are doing is putting a new reference to your copy which no way is going to modify your orginal object.

When you use a ref keyword you are passing the reference to those types ,not a copy

But when you call ChangeFruit(myFruit);. you are passing a copy of the reference of your container.which points to the same object on the heap. and you are modifying the contents of it .

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