以下应用程序演示了如何订阅和取消订阅事件。您可以将此代码放在新的控制台应用程序中以运行它。
它表明第一次引发事件时,会调用您的事件处理程序,然后自行取消订阅。第二次,不再订阅任何处理程序,也没有任何反应。
using System;
class Program
{
static void Main(string[] args)
{
MyClass c = new MyClass();
Console.WriteLine("Ready..");
Console.ReadLine();
}
}
public class MyClass
{
OtherClass otherClassObj = new OtherClass();
public MyClass()
{
Console.WriteLine("Class constructor.. adding event");
otherClassObj.OnMyDataReceived += analyzeValues;
Console.WriteLine("Raising event 1");
otherClassObj.Raise();
Console.WriteLine("Raising event 2");
otherClassObj.Raise();
}
private void analyzeValues(object sender, EventArgs e)
{
Console.WriteLine("Event handler");
Console.WriteLine("Removing event");
otherClassObj.OnMyDataReceived -= analyzeValues;
}
}
public class OtherClass
{
public event EventHandler OnMyDataReceived;
public void Raise()
{
if (OnMyDataReceived != null)
{
OnMyDataReceived(this, EventArgs.Empty);
}
}
}