如何检查事件是否已触发?

3

我在代码实现方面遇到了困难。我目前正在使用PushSharp库,其中一件我想做的事情是,如果事件被触发,我想根据事件返回一个true或false的值。以下是代码:

public static bool SenddNotification()
{
var push = new PushBroker();

        //Wire up the events for all the services that the broker registers
        push.OnNotificationSent += NotificationSent;
        push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;

}


static bool DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
    {
        //Currently this event will only ever happen for Android GCM
        Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        return false;
    }

    static bool NotificationSent(object sender, INotification notification)
    {
        Console.WriteLine("Sent: " + sender + " -> " + notification);
        return true;
    }

如果事件触发,希望返回true或false取决于发生了什么,然后最终在第一个方法中返回此值。


这种情况是要么这个要么那个,还是有时候两者都会触发? - PiousVenom
不应该出现两个同时触发的情况。 - user2094139
1
我建议创建一个全局布尔变量,在事件中返回它,然后在第一个方法中也返回它。但是,这并不太美观。 - PiousVenom
说实话,我不知道那是什么意思,也不知道该如何解决 :P 所以...即使它不太好看!任何帮助都会很好。 - user2094139
1个回答

3
您可以设置一个全局布尔变量,并让您的事件设置该变量,然后让您的第一个方法返回它。类似这样的代码:
private bool globalBool;

public static bool SenddNotification()
{
var push = new PushBroker();

        //Wire up the events for all the services that the broker registers
        push.OnNotificationSent += NotificationSent;
        push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;

        return globalBool;  
}


static bool DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
    {
        //Currently this event will only ever happen for Android GCM
        Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        globalBool = false;
    }

    static bool NotificationSent(object sender, INotification notification)
    {
        Console.WriteLine("Sent: " + sender + " -> " + notification);
        globalBool = true;
    }

当然,在返回值之前,您必须检查它是否为null,并适当处理。

为什么我需要检查 null 呢? - user2094139
哦,算了吧...如果没有任何事件触发。 - user2094139
1
@user2094139:确切地说,如果没有事件触发,它将返回null,这可能会产生不良后果。 - PiousVenom
所以我遇到了一些问题 1)名称在上下文中不存在 2)它说我有错误的返回类型.. - user2094139
@user2094139:它们都是同一个类的一部分吗? - PiousVenom
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接