事件未调用 C#
Event is not Called C#
我目前正在制作一个 NFC 库,当卡片被成功读取时,我需要在其中引发一个事件。
在我的 MainProject 中,我这样调用库:
reader = new NfcReader();
if (reader.Initialize())
{
reader.UidReceived += (s, args) =>
DisplayText(String.Format("UID received: {0}", args.Uid));
}
我的图书馆:
public class NfcReader
{
private SCardMonitor monitor;
public event EventHandler<NfcReaderEventArgs> UidReceived;
public bool Initialize()
{
// When a card is inserted, an event is raised
// then I want to read the Uid of the card
monitor = new SCardMonitor(new SCardContext(), SCardScope.System);
monitor.CardInserted += (s,a) => GetUid(a.ReaderName);
return true;
}
private void GetUid(string readerName)
{
string uid = MyUidGetter(readerName);
OnUidReceived(uid);
}
private void OnUidReceived(string uid)
{
var handler = UidReceived;
if (handler == null)
{
handler(this, new NfcReaderEventArgs(uid));
}
}
}
调试器逐步执行 handler(this, new NfcReaderEventArgs(uid));
,但未调用 DisplayText
方法。有什么想法吗?
我猜你检查处理程序是否为空是一个错字? ;)
也许您的 Initialize return 错误。调试器会逐步执行,因为它不会调用任何东西。这是由 if.
确定的
我建议您改用 handler != null 并确保 Initialize returns 为真。
我目前正在制作一个 NFC 库,当卡片被成功读取时,我需要在其中引发一个事件。
在我的 MainProject 中,我这样调用库:
reader = new NfcReader();
if (reader.Initialize())
{
reader.UidReceived += (s, args) =>
DisplayText(String.Format("UID received: {0}", args.Uid));
}
我的图书馆:
public class NfcReader
{
private SCardMonitor monitor;
public event EventHandler<NfcReaderEventArgs> UidReceived;
public bool Initialize()
{
// When a card is inserted, an event is raised
// then I want to read the Uid of the card
monitor = new SCardMonitor(new SCardContext(), SCardScope.System);
monitor.CardInserted += (s,a) => GetUid(a.ReaderName);
return true;
}
private void GetUid(string readerName)
{
string uid = MyUidGetter(readerName);
OnUidReceived(uid);
}
private void OnUidReceived(string uid)
{
var handler = UidReceived;
if (handler == null)
{
handler(this, new NfcReaderEventArgs(uid));
}
}
}
调试器逐步执行 handler(this, new NfcReaderEventArgs(uid));
,但未调用 DisplayText
方法。有什么想法吗?
我猜你检查处理程序是否为空是一个错字? ;)
也许您的 Initialize return 错误。调试器会逐步执行,因为它不会调用任何东西。这是由 if.
确定的我建议您改用 handler != null 并确保 Initialize returns 为真。