Delegate, Event
Delegate其实就相当于C++/C里面的函数指针.用法如下:
1.最常规的使用
class Program
{
public delegate void NumberChangedEventHandler(int number);
class Publisher
{
public NumberChangedEventHandler NumberChanged;
}
class Subscriber
{
public void OnNumberChanged(int number)
{
string message = "New value is " + number;
Console.WriteLine(message);
}
}
static void Main(string[] args)
{
Publisher pub = new Publisher();
Subscriber sub1 = new Subscriber();
Subscriber sub2 = new Subscriber();
pub.NumberChanged += new NumberChangedEventHandler(sub1.OnNumberChanged);
pub.NumberChanged += new NumberChangedEventHandler(sub2.OnNumberChanged);
pub.NumberChanged(3);
Console.WriteLine("over");
}
}
2.直接当成函数指针用
class Program
{
public delegate void NumberChangedEventHandler(int number);
class Publisher
{
public NumberChangedEventHandler NumberChanged;
}
class Subscriber
{
public void OnNumberChanged(int number)
{
string message = "New value is " + number;
Console.WriteLine(message);
}
}
static void Main(string[] args)
{
Publisher pub = new Publisher();
Subscriber sub1 = new Subscriber();
pub.NumberChanged = sub1.OnNumberChanged;
pub.NumberChanged(3);
}
}
3.异步调用
class Program
{
public delegate void NumberChangedEventHandler(int number);
class Publisher
{
public NumberChangedEventHandler NumberChanged;
}
class Subscriber
{
public void OnNumberChanged(int number)
{
string message = "New value is " + number;
Console.WriteLine(message);
}
}
static void Main(string[] args)
{
Publisher pub = new Publisher();
Subscriber sub1 = new Subscriber();
pub.NumberChanged += new NumberChangedEventHandler(sub1.OnNumberChanged);
pub.NumberChanged.BeginInvoke(3, null, null);
}
}