我知道通过使用ref
关键字,可以在方法中引用另一个对象。在该方法内部的以下示例中创建的对象也可用于该方法之外。如何保留对当前对象中另一个对象的引用
public Method(ref OtherClass input)
{
input = new OtherClass();
}
但我需要领先一步。我需要将引用作为属性保留在对象中,并且在将来需要其他方法时随时更改原始对象。
public class CLass1
{
OtherClass _input;
public Bind(ref OtherClass input)
{
input = new OtherClass(); // instantiating the object
_input = input; // keeping a reference of the created object for later usage!
}
public void Unbind()
{
_input = null;
}
}
当我Bind
对象有一个新的对象初始化原始对象,这正是我想要的。但在此之后,我运行Unbind()
只有_ input
变为空,并且input
保持不变。我需要的input
也变为空!这怎么可能?
有时全局变量是缓解压力的那么有用.....(开个玩笑,我不认为这是可能的,让我们来看看,如果有人有治愈) – Steve
这是不可能的,因为这样,你会必须有某种事件系统,或者使用这个类的属性来实现这一点。 –
请看这里http://stackoverflow.com/a/7253417/3888877 –