如何保存供以后使用参考变量? [英] How to save a ref variable for later use?

查看:136
本文介绍了如何保存供以后使用参考变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这个工作。

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



但是否有可能做这样的事情?

But is it possible to do something like this?

private Apple myApple;

public MyClass(ref Apple apple)
{
    myApple = apple;
}

public void ModifyApple()
{
    myApple = new Apple("Macintosh"); // does not change the input variable like the first example did
}

当裁判变量被复制到成员变量 myApple 它似乎失去了它的'裁判岬,并重新分配不再它改变了输入变量。有没有办法解决?

When the ref variable is copied to the member variable myApple it appears to lose it's 'ref-ness' and re-assigning it no longer changes the input variable. Is there a way around this?

推荐答案

不是真的,没有。通过你的代码下次调用的时候,作为方法参数的原始变量可能甚至不再存在:

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);
}



在这里,苹果是的本地的变量,其中将被弹出通过我们称之为 ModifyApple 时的堆栈帧。

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<T>
{
    public T Value { get; set; }
}

然后在传递 MutableWrapper<苹果> ,并存储在你的类。然后在 ModifyApple 你可以写:

Then pass in a MutableWrapper<Apple>, 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.

说实话,这样的事情往往做出难以维护的代码,甚至 REF 不是很大的可读性。如果你能解释一下你想达到什么样的大局观,我们也许能够提出更好的整体办法。

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.

这篇关于如何保存供以后使用参考变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆