以下是發送和註冊代碼的快速部分。您的通知是指示接收方意圖是什麼的信息。內容是您想要發送的項目,您可以進一步識別發送消息的人員,甚至是此消息針對發件人和目標的目標。
Messenger.Default.Send<NotificationMessage<Job>>(
new NotificationMessage<Job>(this, myJob, "Add")
);
Messenger.Default.Register<NotificationMessage<Job>>(
this, nm =>
{
// this might be a good idea if you have multiple recipients.
if (nm.Target != null &&
nm.Target != this)
return;
// This is also an option
if (nm.Sender != null &&
nm.Sender != expectedFrom) // expectedFrom is the object whose code called Send
return;
// Processing the Message
switch(nm.Notification)
{
case "Add":
Job receivedJob = nm.Content;
// Do something with receivedJob
break;
case "Delete":
Job receivedJob = nm.Content;
// Do something with receivedJob
break;
}
});
令牌可以是任何對象,而不僅僅是接收正確的類型? – nportelli 2010-08-06 18:07:16
這是正確的,令牌與接收者無關,它只是一個對象(或像int這樣的值)。如果你喜歡,它是一個標識符。 – LBugnion 2010-08-11 09:54:35
@LBugnion如果Ryan的回答是針對這個問題的最佳做法,你能評論嗎?或者你可以發佈你如何實現它?謝謝 – GONeale 2012-06-14 03:29:30