1.原始的委托 (.net 1.0)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsFormsAppLINQ { public partial class Form1 : Form { public delegate void MyDelegate(); public Form1() { InitializeComponent(); MyDelegate myDelegate = new MyDelegate(DoSomething); myDelegate(); } public void DoSomething() { MessageBox.Show("Hello"); } } }
2.Action预定义委托, 节省了委托的定义.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsAppLINQ { public partial class Form2 : Form { public Form2() { InitializeComponent(); Action myDelegate = new Action(DoSomething); myDelegate(); } public void DoSomething() { MessageBox.Show("Hello"); } } }
3.Lambda表达式, 再省掉方法定义.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsAppLINQ { public partial class Form3 : Form { public Form3() { InitializeComponent(); Action myDelegate = new Action(() => { MessageBox.Show("Hello"); }); myDelegate(); } } }
4.一对小括号, 直接执行.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsAppLINQ { public partial class Form4 : Form { public Form4() { InitializeComponent(); new Action(() => { MessageBox.Show("Hello"); })(); } } }
总结,()=> {} 这个lambda表达式就是一个无参数的委托及具体方法的组合体,这是一个常规的套路,可以直接记住。