日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > C# >内容正文

C#

c#匿名方法用途_C#的匿名方法

發(fā)布時(shí)間:2024/10/8 C# 105 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c#匿名方法用途_C#的匿名方法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

匿名方法是在初始化委托時(shí)內(nèi)聯(lián)聲明的方法。

例如下面這兩個(gè)例子:

不使用匿名方法的委托:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplication7

{classProgram

{public static int add(int x)

{

return x + 20;

}delegate int otherdel(intparam);public static voidMain()

{

otherdel del=add;

Console.WriteLine("{0}", del(20));

Console.WriteLine("{0}", del(10));

}

}

}

使用匿名方法的委托:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplication7

{classProgram

{delegate int otherdel(intparam);public static voidMain()

{

otherdel del= delegate(int x)

{

return x + 20;

};

Console.WriteLine("{0}", del(20));

Console.WriteLine("{0}", del(10));

}

}

}

兩種結(jié)果是一樣的。

使用匿名方法

1)聲明委托變量時(shí)候作為初始化表達(dá)式。

2)組合委托時(shí)在賦值語句的右邊。

3)為委托增加事件時(shí)在賦值語句的右邊。

匿名方法語法

delegate (parameters ){implementationcode};

關(guān)鍵字  參數(shù)        語句塊

匿名方法不會(huì)聲明返回值類型。但是匿名方法返回值類型必須和委托返回值一樣。

參數(shù):參數(shù)數(shù)量,類型和修飾符必須和委托一樣。

但是我們可以使圓括號(hào)為空,或省略圓括號(hào)來簡(jiǎn)化匿名方法的參數(shù)列表。但是僅在下面兩項(xiàng)都為真的情況下才可以這么做。

1,委托的參數(shù)列表不包含任何out參數(shù)的委托。

2,匿名方法不使用任何參數(shù)。

例如下面:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplication7

{classProgram

{delegate int otherdel(intparam);public static voidMain()

{

otherdel del= delegate{

cleanup();

printMessage();

};

}

}

}

params參數(shù):

如果委托參數(shù)包含params參數(shù),那么params關(guān)鍵字就會(huì)被匿名方法的參數(shù)列表忽略。如下:

delegate int otherdel(int x,params inty);

otherdel del= delegate(int x,inty)

{-------------};

總結(jié)

以上是生活随笔為你收集整理的c#匿名方法用途_C#的匿名方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。