事件不叫C#

时间:2016-01-07 14:34:14

标签: c# lambda event-handling

我目前正在制作一个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方法。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我猜你检查处理程序是否为空是一个错字? ;)

也许你的Initialize确实返回false。调试器完全是因为它不会调用任何东西。这是由if。

确定的

我建议您使用handler!= null,并确保Initialize返回true。