+-
如何检查事件是否触发了C#
大家好,我在执行代码方面遇到麻烦.我目前正在使用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,然后最终在第一个方法中返回此值

最佳答案
您可以设置一个全局布尔变量,并让您的事件设置该变量,然后让您的第一个方法将其返回.像这样:

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并进行适当处理.

点击查看更多相关文章

转载注明原文:如何检查事件是否触发了C# - 乐贴网