我有 3 个类,即 Login、Barcode 和 Main。
登录类仅包含用户的身份验证。
条形码类具有以下片段代码:
class Barcode
{
public delegate void BarcodeReadHandler(object sender, BarcodeEventArgs e);
public event BarcodeReadHandler BarcodeReadOut;
public Barcode()
{
//.. some codes for getting data on the scanner
BarcodeEventArgs args = new BarcodeEventArgs(scannedData);
BarcodeReadOut(this, args);
}
}
在Main类中,Barcode事件的订阅完成:
public partial class Main : Form
{
private Barcode barcode = null;
public Main()
{
barcode.BarcodeReadOut += new barcode.BarcodeReadHandler(getBarcodeStr);
}
//This is called before log-out.
public void removeInstance()
{
barcode.BarcodeReadOut -= new barcode.BarcodeReadHandler(getBarcodeStr);
}
private void getBarcodeStr(object sender, BarcodeEventArgs e)
{
//some code
}
}
当我尝试注销并再次登录时,事件订阅发生重复。
当我尝试调试时,BarcodeReadOut 被调用了两次。
注销时,调用 removeInstance() 并且在打开登录屏幕之前主窗体是 Close() 和 Dispose()。
有人可以帮助我避免重复上述事件吗?
我在注册事件之前也这样做了,但没有任何反应:
public Main()
{
barcode.BarcodeReadOut -= new barcode.BarcodeReadHandler(getBarcodeStr);
barcode.BarcodeReadOut += new barcode.BarcodeReadHandler(getBarcodeStr);
}
最佳答案
您应该按如下方式添加和删除处理程序:
public partial class Main : Form
{
private Barcode barcode = null;
public Main()
{
barcode.BarcodeReadOut += getBarcodeStr;
}
//This is called before log-out.
public void removeInstance()
{
barcode.BarcodeReadOut -= getBarcodeStr;
}
private void getBarcodeStr(object sender, BarcodeEventArgs e)
{
//some code
}
}
此外:您不需要定义自定义委托(delegate),您可以使用通用的EventHandler
:
public event EventHandler<BarcodeEventArgs> BarcodeReadOut;
关于c# - 如何避免重复订阅事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31555010/