c 匿名方法用途 C 匿名方法

2021-10-16 15:49:00 字數 1638 閱讀 1579

c#語言 的 c#匿名方法

前面我們學習過,委託可用於引用任何與委託簽名相同的方法。換句話說,可以呼叫可以由委託使用該委託物件引用的方法。

匿名方法提供了一種將**塊作為委託引數傳遞的技術。匿名方法是沒有名稱的方法,只有方法體。

不需要在匿名方法中指定返回型別; 它是從方法體中的return語句來推斷的。

編寫匿名方法

使用delegate關鍵字建立**例項時,就可以宣告匿名方法。 例如,

delegate void numberchanger(int n);

numberchanger nc = delegate(int x)

console.writeline("anonymous method: ", x);

**塊console.writeline("anonymous method: ", x);是匿名方法體。

**可以使用匿名方法和命名方法以相同的方式呼叫,即通過將方法引數傳遞給委託物件。

例如,nc(10);

示例以下示例演示如何實現概念:

using system;

delegate void numberchanger(int n);

class testdelegate

static int num = 10;

public static void addnum(int p)

num += p;

console.writeline("named method: ", num);

public static void multnum(int q)

num *= q;

console.writeline("named method: ", num);

public static int getnum()

return num;

static void main(string args)

//create delegate instances using anonymous method

numberchanger nc = delegate(int x)

console.writeline("anonymous method: ", x);

//calling the delegate using the anonymous method

nc(10);

//instantiating the delegate using the named methods

nc = new numberchanger(addnum);

//calling the delegate using the named methods

nc(5);

//instantiating the delegate using another named methods

nc = new numberchanger(multnum);

//calling the delegate using the named methods

nc(2);

console.readkey();

當上述**被編譯並執行時,它產生以下結果:

anonymous method: 10

named method: 15

named method: 30

c 匿名方法用途 C 匿名方法

我們討論了使用委託來引用具有與委託相同簽名的任何方法。換句話說,您可以使用該委託物件呼叫可由委託引用的方法。匿名方法提供了一種將 塊作為委託引數傳遞的技術。匿名方法是沒有名稱的方法,只是主體。您無需在匿名方法中指定返回型別 它是從方法體內的return語句推斷出來的。編寫匿名方法 匿名方法是通過建立...

C 匿名方法

1,匿名方法 c 為委託提供一種機制,可以為委託定義匿名方法,匿名方法沒有名稱,編譯器會定指定乙個名稱 匿名方法中不能使用跳轉語句跳轉到該匿名方法的外部,也不能跳轉到該方法的內部。也不能在匿名方法外部使用的ref和out引數 2,匿名方法的 拉姆達 表示式 方式定義 c 3.0之後匿名方法可以使用 ...

c 匿名方法

例如下面這兩個例子 不使用匿名方法的委託 using system using system.collections.generic using system.linq using system.text namespace delegate int otherdel int param publi...