How to save a ref variable for later use?

前端 未结 4 702
忘掉有多难
忘掉有多难 2020-12-18 20:15

So this works..

public MyClass(ref Apple apple)
{
    apple = new Apple(\"Macintosh\"); // Works fine
}

But is it possible to do something

4条回答
  •  情歌与酒
    2020-12-18 20:27

    No, there isn't. myApple is a field that holds a reference to an Apple; the parameter apple, however, is actually a reference-to-a-reference-to-an-Apple. When you assign apple to myApple you dereference the value of the parameter. Beyond that, they are separate and distinct.

    So no: it is not possible.

    What would be possible is to have something like:

    public class AppleWrapper {
        public Apple Value {get;set;}
    }
    

    Now; if you store an AppleWrapper, any number of callers can access and change the .Value

提交回复
热议问题