【发布时间】:2025-08-27 09:25:02
【问题描述】:
我知道通过使用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 变为空!这怎么可能?
【问题讨论】:
-
有时全局变量对于缓解压力非常有用.....(开玩笑的,我不认为这是可能的,让我们看看是否有人能治愈)
-
这是不可能的,你必须有某种事件系统,或者在任何地方使用这个类的属性来实现这一点。
-
这就是事件的用途。您的班级可以在
input更改的任何时候引发事件,并且任何其他需要了解input更改的班级都可以订阅该事件。
标签: c# reference parameter-passing pass-by-reference