C#用Lambda和委托實現(xiàn)模板方法
1 問題描述
查看下面這段代碼:
int[] a = [1,2,3];
for (int i =0; i<a.length; i++)
{
a[i] = a[i] * 2;
}
for (int i =0; i<a.length; i++)
{
Console.WriteLine(a[i]);
}
很明顯,上述代碼中存在for循環(huán)的重復代碼。
2 解決方案
如何消除重復?使用委托。
•定義委托
delegate int mapfun(int x);//以替換上述代碼中不同的部分
•模板方法
//只負責遍歷
void map(mapfun fn, int[] a)
{
for (int i = 0; i < a.Length; ++i)
{
a[i] = fn(a[i]);
}
}
•客戶端代碼
int[] a = {1, 2, 3};
map(delegate(int x) { return x * 2; }, a); //.Net 2.0支持委托匿名方法
map(x => { Console.WriteLine(x); return x; }, a); //.Net 3.0開始支持lambda表達式
3 完整代碼示例
class Program
{
static void Main(string[] args)
{
int[] a = {1, 2, 3};
map(delegate(int x) { return x * 2; }, a); //.Net 2.0支持委托匿名方法
map(x => { Console.WriteLine(x); return x; }, a); //.Net 3.0開始支持lambda表達式
}
delegate int mapfun(int x);
static void map(mapfun fn, int[] a)
{
for (int i = 0; i < a.Length; ++i)
{
a[i] = fn(a[i]);
}
}
}
4 與傳統(tǒng)模板方法的比較
1.減少了子類數(shù)量,模板方法中,拓展一套算法就需要一個子類。
2.模板將算法隱藏,委托交由客戶代碼去選擇。
相關文章
Unity2021發(fā)布WebGL與網(wǎng)頁交互問題的解決
本文主要介紹了Unity2021發(fā)布WebGL與網(wǎng)頁交互問題的解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05C#請求http向網(wǎng)頁發(fā)送接收數(shù)據(jù)的方法
這篇文章主要為大家詳細介紹了C#請求http向網(wǎng)頁發(fā)送數(shù)據(jù)、網(wǎng)頁接收的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07