清理(委托类型实例)事件处理(实例)的函数及Lambda表达式
1 namespace Microshaoft 2 { 3 using System; 4 using System.Linq; 5 using System.Drawing; 6 using System.Collections.Generic; 7 using System.Windows.Forms; 8 public class Form1 : Form 9 { 10 static void Main() 11 { 12 Application.Run(new Form1()); 13 } 14 //private List<Action<object, EventArgs>> _actions = null; 15 //private List<EventHandler> _eventHandlers = null; 16 private Button button1; 17 public Form1() 18 { 19 button1 = new Button(); 20 button1.Text = "button1"; 21 Controls.Add(button1); 22 23 var actions = new List<Action<object, EventArgs>>(); 24 //_actions = actions; 25 var eventHandlers = new List<EventHandler>(); 26 //_eventHandlers = eventHandlers; 27 //int i = 1; 28 EventHandler eh; 29 eh = new EventHandler 30 ( 31 (x, y) => 32 { 33 MessageBox.Show("Lambda1"); 34 DisposeHandlersAllProcesses(eventHandlers); 35 } 36 ); 37 eventHandlers.Add(eh); 38 eventHandlers.Add(eh); 39 //_actions.Add(eh); 40 //_actions.Add(eh); 41 eventHandlers 42 //_actions 43 .ForEach 44 ( 45 (x) => 46 { 47 button1.Click += eh; 48 button1.Click += 49 ( 50 (xx, yy) => 51 { 52 MessageBox.Show("Lambda2"); 53 DisposeHandlersAllProcesses(eventHandlers); 54 } 55 ); 56 } 57 ); 58 button1.Click -= eh; 59 eh = null; 60 DisposeHandlersAllProcesses(eventHandlers); 61 //(EventHandler) _action; 62 //new EventHandler 63 } 64 //private void DisposeHandlersAllProcesses(List<Action> handlers) 65 private void DisposeHandlersAllProcesses(List<EventHandler> handlers) 66 { 67 handlers 68 //_actions 69 .ForEach 70 ( 71 (x) => 72 { 73 var invocations = x.GetInvocationList(); 74 Array.ForEach 75 ( 76 invocations 77 , (xx) => 78 { 79 x -= (EventHandler)xx; 80 Console.WriteLine("{0}:{1}", x, xx); 81 } 82 ); 83 x = null; 84 } 85 ); 86 } 87 } 88 }