星期二, 9月 09, 2008

用Lambda運算式來代替Anonymous Function(匿名函式)

直接看簡單例子..

using System;
using System.Web;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
person p = new person();
bathroom b = new bathroom();

//加入事件要執行的methods
p.AddSchedule(b.Urinate);
p.AddSchedule(b.Defecate);
p.AddSchedule(() => b.TakeAShower(30));//用lamda運算式去取代2.0的匿名方法

//執行
p.RunOfSchedule();
}
}
delegate void MySchedule();
class person
{
public event MySchedule RunSchedule;
public void AddSchedule(MySchedule s)
{
RunSchedule += s;
}
public void RunOfSchedule()
{
if (RunSchedule != null)
RunSchedule();
}
}
class bathroom
{
Page pg = HttpContext.Current.CurrentHandler as Page;
public void TakeAShower(int time)
{
pg.Response.Write(string.Format("{0}分鐘洗澡<br />", time));
}
public void Defecate()
{
pg.Response.Write("大便<br />");
}
public void Urinate()
{
pg.Response.Write("尿尿<br />");
}
}

上面是簡單的兩個class..為person寫事件..在建構式時加入事件..然後去執行..DevilDevilDevilDevilDevilDevil..

參考:
http://msdn.microsoft.com/zh-tw/library/bb882516.aspx

沒有留言: