c#匿名方法用途_C#的匿名方法
匿名方法是在初始化委托時內聯聲明的方法。
例如下面這兩個例子:
不使用匿名方法的委托:
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));
}
}
}
兩種結果是一樣的。
使用匿名方法
1)聲明委托變量時候作為初始化表達式。
2)組合委托時在賦值語句的右邊。
3)為委托增加事件時在賦值語句的右邊。
匿名方法語法
delegate (parameters ){implementationcode};
關鍵字 參數 語句塊
匿名方法不會聲明返回值類型。但是匿名方法返回值類型必須和委托返回值一樣。
參數:參數數量,類型和修飾符必須和委托一樣。
但是我們可以使圓括號為空,或省略圓括號來簡化匿名方法的參數列表。但是僅在下面兩項都為真的情況下才可以這么做。
1,委托的參數列表不包含任何out參數的委托。
2,匿名方法不使用任何參數。
例如下面:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplication7
{classProgram
{delegate int otherdel(intparam);public static voidMain()
{
otherdel del= delegate{
cleanup();
printMessage();
};
}
}
}
params參數:
如果委托參數包含params參數,那么params關鍵字就會被匿名方法的參數列表忽略。如下:
delegate int otherdel(int x,params inty);
otherdel del= delegate(int x,inty)
{-------------};
總結
以上是生活随笔為你收集整理的c#匿名方法用途_C#的匿名方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql实现俩个属性加减运算_SQL实
- 下一篇: gsonformat安装怎么使用_IDE