gpt4 book ai didi

c# - 传递实例对象时事件订阅丢失

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:59 24 4
gpt4 key购买 nike

我创建了一个带有事件 (TheEvent) 的外部类 (TheClass) 并从另一个类的 Panel 构造函数中订阅它:

public aPanel()
{
...
theClassInstance.TheEvent += new WaitCallback(aMethod);
...
}

稍后在程序中,我调用了一个将theClassInstance 作为唯一参数传递的方法

bMethod((object)theClassInstance);

在哪里

public void bMethod(object inputTheClassInstance)
{
...
}

知道输入对象是 TheClass 类型,我执行以下操作:

public void bMethod(object inputTheClassInstace)
{
TheClass theClassInput = (TheClass)inputTheClassInstace;
...
}

稍后在 bMethod() 中,我调用了 theClassInput 公开的方法 RaiseEvent(),它实际上会触发事件。在 RaiseEvent() 我有

if(this.TheEvent != null)
TheEvent();

确保某些内容已订阅该事件,但 this.TheEvent 等于 null。如果我将订阅放在 bMethod()

bMethod(...)
{
...
theClassInput.TheEvent += new WaitCallback(aMethod);
...
}

它工作得很好,但我想将它保留在 Panel 的构造函数中。我认为因为 theClassInput 指向与 theClassInstance 相同的对象,所以触发事件不会有什么不同。关于如何在使用 theClassInputbMethod() 中调用它的同时将订阅保留在构造函数中有什么想法吗?

最佳答案

传递对象不会清除事件处理程序。您必须在途中的某处不小心创建了一个新对象,而不是传递原始对象。

关于c# - 传递实例对象时事件订阅丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6850233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com