简单的事件多播
Code
class Program
{
public delegate void MyEventHandler();
public static void Method1() { Console.WriteLine("Method1"); }
public static void Method2() { Console.WriteLine("Method2"); }
public static void Method3() { Console.WriteLine("Method3"); }
static void Main(string[] args)
{
MyEventHandler myHandler = null;
myHandler += new MyEventHandler(Method1);
myHandler += new MyEventHandler(Method2);
myHandler += new MyEventHandler(Method3);
myHandler.Invoke();
Console.ReadKey();
}
}
class Program
{
public delegate void MyEventHandler();
public static void Method1() { Console.WriteLine("Method1"); }
public static void Method2() { Console.WriteLine("Method2"); }
public static void Method3() { Console.WriteLine("Method3"); }
static void Main(string[] args)
{
MyEventHandler myHandler = null;
myHandler += new MyEventHandler(Method1);
myHandler += new MyEventHandler(Method2);
myHandler += new MyEventHandler(Method3);
myHandler.Invoke();
Console.ReadKey();
}
}
1:自定义的delegate类型继承自MuticastDelegate,这是多播机制他娘
2:多播的顺序是不可控的,虽然看到的实验结果是依次执行,但不要依赖这个顺序实现你的业务
3:在给多播增加事件的时候可以直接用匿名委托或lambda表达式,形如:
myHandler += delegate { Console.WriteLine("from unname delegate"); };
myHandler += ()=>Console.WriteLine("from lambda");
注意:在工程化实现的时候以上方法不太可取。
再来一种形式的多播
代码
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public delegate void MemoHandler(string s);
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Type type = typeof(MemoHandler);
Delegate d = Delegate.CreateDelegate(type, new C1(), "A1");
d = Delegate.Combine(d, Delegate.CreateDelegate(type, new C2(), "A2"));
MemoHandler handler = (MemoHandler)d;
handler.Invoke("amazing!!!");
}
}
public class C1
{
public void A1(string s)
{
MessageBox.Show(s);
}
}
public class C2
{
public void A2(string s)
{
MessageBox.Show(s);
}
}