How to save a ref variable for later use?

前端 未结 4 711
忘掉有多难
忘掉有多难 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:34

    Not really, no. By the time your code is next invoked, the original variable used as the method argument may no longer even exist:

    void Foo()
    {
        MyClass x = Bar();
        x.ModifyApple();
    }
    
    MyClass Bar()
    {
        Apple apple = new Apple();
        return new MyClass(ref apple);
    }
    

    Here, apple is a local variable, in a stack frame which will have been popped by the time we call ModifyApple.

    Are you sure you need to modify the original caller's variable rather than just changing the object itself?

    One way to sort of fake this would be to use a wrapper type to start with:

    public class MutableWrapper
    {
        public T Value { get; set; }
    }
    

    Then pass in a MutableWrapper, and store that in your class. Then in ModifyApple you can write:

    wrapper.Value = new Apple();
    

    This won't change the caller's variable, but next time the caller looks at the Value property, they'll see your new apple.

    To be honest, this sort of thing tends to make for hard-to-maintain code, and even ref isn't great for readability. If you can explain the bigger picture of what you're trying to achieve, we may be able to suggest a better overall approach.

提交回复
热议问题