开发者

Why does this only work when the ref keyword is used?

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 ChangeF开发者_如何学JAVAruit, 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.


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 .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜