当前位置: 代码迷 >> 综合 >> C# 委托 匿名委托 Lambda 理解
  详细解决方案

C# 委托 匿名委托 Lambda 理解

热度:78   发布时间:2023-10-30 16:29:46.0

委托是强声明一个委托,但是委托声明过多会很繁杂,所以有匿名委托【或者说匿名方法】,不需要指定委托名就可以使用;匿名方法还是要写一长串单词,为了更简化就使用Lambda。但三者本质都一样,或者说当你的代码编译后匿名和lambda编译器其实还是会生成个委托声明的。`

    private delegate void Explicit_Dele();private void button1_Click(object sender, EventArgs e){this.textBox1.Text= TraditonalDelegeteSyntax();}//需要委托的方法private static bool IsEvenNumber(int i){return (i % 2) == 0;}static string TraditonalDelegeteSyntax(){//通过泛型定义列表数组List<int> list = new List<int>();list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });//显示声明委托Predicate<int> callback = new Predicate<int>(IsEvenNumber);//有名字的委托List<int> evenNumbers = list.FindAll(callback);string s = "";foreach (int evenNumber in evenNumbers){s += $"{evenNumber}\t";}//Console.WriteLine();return s;}//匿名委托static string AnonymousDelegeteSyntax(){//通过泛型定义列表数组List<int> list = new List<int>();list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });//显示声明委托List<int> evenNumbers = list.FindAll(delegate(int i) { return (i % 2) == 2; });string s = "";foreach (int evenNumber in evenNumbers){s += $"{evenNumber}\t";}//Console.WriteLine();return s;}//Lamddastatic void LambdaExpressionSyntax(){//通过泛型定义列表数组List<int> list = new List<int>();list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });//实现LamddaList<int> evenNumbers = list.FindAll(i=>(i%2==0));foreach (int evenNumber in evenNumbers){Console.Write("{0}\t", evenNumber);}Console.WriteLine();}`
  相关解决方案