1.什么是委托的,看例子
public partial class WebForm5 : System.Web.UI.Page { public delegate void SayHelloDelegate(string name); protected void Page_Load(object sender, EventArgs e) { SayHelloDelegate dlg1 = ChineseHello; dlg1("lingx"); } public void ChineseHello(string name) { lb.Text = "你好," + name; } }
运行结果:你好,lingx
在例子中可以看出可以通过声明一个参数是(sting),无返回值的的委托。再把一个参数是(sting),无返回值ChineseHello的方法绑定委托,就可以通过委托调用方法。这最简单的调用。
2.用委托做为参数传递(可以大大的提高程序的灵活性)
public partial class WebForm5 : System.Web.UI.Page { public delegate void SayHelloDelegate(string name); protected void Page_Load(object sender, EventArgs e) { GreetPeople("lingx", EnglishHello); } public void GreetPeople(string name, SayHelloDelegate MakeGreeting) { MakeGreeting(name); } public void ChineseHello(string name) { lb.Text = "你好," + name; } public void EnglishHello(string name) { lb.Text = "Hello," + name; } }
运行结果:hello,lingx
3.使用Action 和Func
Action 没有返回值的委托
Func 有返回值的委托
通过使用Action我们上面的代码,可以这样写
public partial class WebForm5 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GreetPeople("lingx", EnglishHello); } public void GreetPeople(string name, Action<string> MakeGreeting) { MakeGreeting(name); } public void ChineseHello(string name) { lb.Text = "你好," + name; } public void EnglishHello(string name) { lb.Text = "Hello," + name; } }
4.使用lambada表达式
public partial class WebForm5 : System.Web.UI.Page { public delegate string test(string name); protected void Page_Load(object sender, EventArgs e) { GreetPeople("lingx", EnglishHello); } public void GreetPeople(string name, Action<string> MakeGreeting) { MakeGreeting(name); } public void ChineseHello(string name) { test dlg = s => "你好," + name; lb.Text = dlg(name); } public void EnglishHello(string name) { test dlg = s => "Hello," + name; lb.Text = dlg(name); } }
s => "Hello," + name; 等价于delegate(string s){ return "Hello," + name;}
5.lambada日常的使用
public partial class WebForm5 : System.Web.UI.Page { int[] num={1,2,3,4,5}; protected void Page_Load(object sender, EventArgs e) { var a = num.Where(i=>i> 2); int tmp = 0; foreach(int c in a) { tmp = tmp + c; } lb.Text = tmp.ToString(); } }
把数组里面大于2的数找出来,再相加