国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

委托的N種寫(xiě)法,你喜歡哪種?

2019-11-14 13:35:12
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

原文:http://www.survivalescaperooms.com/FreeDong/archive/2013/07/31/3227638.html

一、委托調(diào)用方式

1. 最原始版本:

 

delegate string PlusStringHandle(string x, string y);class PRogram{static void Main(string[] args){PlusStringHandle pHandle = new PlusStringHandle(plusString);Console.WriteLine(pHandle("abc", "edf"));Console.Read();}static string plusString(string x, string y){return x + y;}}

  


2. 原始匿名函數(shù)版:去掉“plusString”方法,改為

PlusStringHandle pHandle = new PlusStringHandle(delegate(string x, string y){return x + y;});Console.WriteLine(pHandle("abc", "edf"));

  


3. 使用Lambda(C#3.0+),繼續(xù)去掉“plusString”方法(以下代碼均不再需要該方法)

PlusStringHandle pHandle = (string x, string y) =>{return x + y;};Console.WriteLine(pHandle("abc", "edf"));還有更甚的寫(xiě)法(省去參數(shù)類型)PlusStringHandle pHandle = (x, y) =>{return x + y;};Console.WriteLine(pHandle("abc", "edf"));如果只有一個(gè)參數(shù) delegate void WriteStringHandle(string str);static void Main(string[] args){//如果只有一個(gè)參數(shù)WriteStringHandle handle = p => Console.WriteLine(p);handle("lisi");Console.Read();}

  

二、委托聲明方式

1. 原始聲明方式見(jiàn)上述Demo
2. 直接使用.NET Framework定義好的泛型委托 Func 與 Action ,從而省卻每次都進(jìn)行的委托聲明。

static void Main(string[] args){WritePrint<int>(p => Console.WriteLine("{0}是一個(gè)整數(shù)", p), 10);Console.Read();}static void WritePrint<T>(Action<T> action, T t){Console.WriteLine("類型為:{0},值為:{1}", t.GetType(), t);action(t);}

  

3. 再加上個(gè)擴(kuò)展方法,就能搞成所謂的“鏈?zhǔn)骄幊?rdquo;啦。

class Program{ static void Main(string[] args){string str = "所有童鞋:".plusString(p => p = p + " girl: lisi、lili/r/n").plusString(p => p + "boy: wangwu") ;Console.WriteLine(str);Console.Read();}}static class Extentions{public static string plusString<TParam>(this TParam source, Func<TParam, string> func){Console.WriteLine("字符串相加前原值為:{0}。。。。。。", source);return func(source);}}

  

看這個(gè)代碼是不是和我們平時(shí)寫(xiě)的"list.Where(p => p.Age > 18)"很像呢?沒(méi)錯(cuò)Where等方法就是使用類似的方式來(lái)實(shí)現(xiàn)的。

好了,我總結(jié)完了,如有遺漏,還望補(bǔ)上,臣不盡感激。

 


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 吉木萨尔县| 阜城县| 松桃| 澳门| 南漳县| 白城市| 洪江市| 林甸县| 禄劝| 灯塔市| 常山县| 洞口县| 织金县| 常州市| 通化县| 科尔| 都兰县| 甘肃省| 望城县| 扎鲁特旗| 石楼县| 扶绥县| 黑河市| 安西县| 淮北市| 丰原市| 乐至县| 萝北县| 河源市| 珠海市| 株洲县| 惠安县| 宜城市| 木兰县| 滁州市| 千阳县| 海城市| 潼南县| 翼城县| 营口市| 泰顺县|