星期日, 3月 23, 2008

Lambda運算式

這是C# 3.0新增的功能..
剛剛試用了一下..發現蠻好用的..
簡單的來說就是delegate的直覺化方式

之前一般我們都是這樣用..

public partial class test_delegate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

delegate int doFunction(int x, int y);
void Button1_Click(object sender, EventArgs e)
{
doFunction myAdd = new doFunction(new count().doAdd);
doFunction myMilus = new doFunction(new count().doMilus);
Response.Write(myAdd(1, 3));
Response.Write("<br />");
Response.Write(myMilus(1, 3));

}
}
class count
{
public int doAdd(int x, int y)
{
int result = x + y;
return result;
}
public int doMilus(int x, int y)
{
int result = x - y;
return result;
}
}

現在可以用樣用..

public partial class test_lambda : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

delegate int doFunction(int x, int y);
void Button1_Click(object sender, EventArgs e)
{
doFunction myAdd = (x, y) =>
{
int result = x + y;
return result;
};
doFunction myMilus = (x, y) =>
{
int result = x - y;
return result;
};

Response.Write(myAdd(1, 2));
Response.Write("<br />");
Response.Write(myMilus(1, 2));
}
}

再生級..

public partial class test_lambda : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
void Button1_Click(object sender, EventArgs e)
{
Func<int, int, int> myAdd = (x, y) =>
{
int result = x + y;
return result;
};
Func<int, int, int> myMilus = (x, y) =>
{
int result = x - y;
return result;
};

Response.Write(myAdd(1, 2));
Response.Write("<br />");
Response.Write(myMilus(1, 2));
}
}

你可以比較一下..這樣直覺簡單多啦~Open-mouthed..

1 則留言:

Ruby 提到...

我要發表意見...發表意見