2013-07-30 213 views
2

嘿傢伙我在執行我的代碼時遇到了麻煩。我目前使用PushSharp庫,我想要做的事情之一是如果事件觸發,我想返回一個真或假的值,取決於它是什麼事件。繼承人的代碼:如何檢查一個事件是否已經觸發C#

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取決於發生了什麼,然後最終在第一種方法返回該值

+0

那麼,這是一種情景還是類型,還是會有兩種情況會發生? – MyCodeSucks

+0

不應該有一個實例,其中既火。 – user2094139

+1

我會說創建一個全局布爾值,並返回你的事件,然後返回它在你的第一個方法。但是,這並不漂亮。 – MyCodeSucks

回答

2

你可以設置一個全局布爾變量,並讓你的事件設置該變量,然後讓你的第一個方法返回它。事情是這樣的:

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,並適當地處理它。

+0

爲什麼我要檢查空? – user2094139

+0

哦nvm ...如果沒有任何事件發生, – user2094139

+1

@ user2094139:正確。如果沒有事件觸發,那麼它將返回null,並且可能會產生不希望的結果。 – MyCodeSucks

相關問題