Я нашел следующий пример делегата/события в онлайн-книге C#. Но то, что я пропустил, это отмена подписки на объект MailWatch, когда он умирает, - что будет правильным способом отменить его подписку?C# делегат, события - как отказаться от подписки?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class NewEmailEventArgs : EventArgs
{
public NewEmailEventArgs (string subject, string message)
{
this.subject = subject;
this.message = message;
}
public string Subject { get { return (subject); } }
public string Message { get { return (message); } }
string subject;
string message;
}
class EmailNotify
{
public delegate void NewMailEventHandler (object sender, NewEmailEventArgs e);
public event NewMailEventHandler OnNewMailHandler;
protected void OnNewMail (NewEmailEventArgs e)
{
if (OnNewMailHandler != null)
OnNewMailHandler(this, e);
}
public void NotifyMail (string subject, string message)
{
NewEmailEventArgs e = new NewEmailEventArgs(subject, message);
OnNewMail(e);
}
}
class MailWatch
{
public MailWatch (EmailNotify emailNotify)
{
this.emailNotify = emailNotify;
emailNotify.OnNewMailHandler += new EmailNotify.NewMailEventHandler(IHaveMail);
}
void IHaveMail (object sender, NewEmailEventArgs e)
{
Console.WriteLine("New Mail:", e.Subject, e.Message);
}
EmailNotify emailNotify;
}
class Test
{
public static void Main()
{
EmailNotify emailNotify = new EmailNotify();
MailWatch mailWatch = new MailWatch(emailNotify);
emailNotify.NotifyMail("Hello!", "Welcome to Events!!!")
}
}
И почему объект MailWatch получает второй NotifyMail? Объект MailWatch уже вышел из сферы действия, и я думаю, что он должен быть уже в байте-нирване?
class Test
{
public static void Main()
{
EmailNotify emailNotify = new EmailNotify();
{
MailWatch mailWatch = new MailWatch(emailNotify);
emailNotify.NotifyMail("1!", "At live.");
}
emailNotify.NotifyMail("2!", "Still alive.");
}
}
Спасибо.
Вы попробовали отказаться от подписки на оператор '- ='? – hellowstone
Возможный дубликат [Отмена конференции] (http://stackoverflow.com/questions/15448258/event-unsubscribe) –
Очень незначительная удобная настройка: 'emailNotify.OnNewMailHandler + = IHaveMail;' - значение идентично; просто проще набирать и читать –