lambda表达式用法——C#学习笔记

"Lambda 表达式"是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型。

实例如下:

代码如下:

cs 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    delegate bool D();
    delegate bool D2(int i);

    class Test
    {
        D del;
        D2 del2;
        public void TestMethod(int input)
        {
            int j = 0;
            // Initialize the delegates with lambda expressions.
            // Note access to 2 outer variables.
            // del will be invoked within this method.
            del = () => { j = 10; return j > input; };

            // del2 will be invoked after TestMethod goes out of scope.
            del2 = (x) => { return x == j; };

            // Demonstrate value of j:
            // Output: j = 0 
            // The delegate has not been invoked yet.
            Console.WriteLine("调用前j = {0}", j);

            // Invoke the delegate.
            bool boolResult = del();

            // Output: j = 10 b = True
            Console.WriteLine("调用后j = {0}. b = {1}", j, boolResult);
        }

        static void Main()
        {
            Test test = new Test();
            test.TestMethod(5);

            // Prove that del2 still has a copy of
            // local variable j from TestMethod.
            bool result = test.del2(10);

            // Output: True
            Console.WriteLine(result);

            Console.ReadKey();
        }
    }



}
相关推荐
charlie1145141911 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
好奇龙猫1 小时前
【AI学习-comfyUI学习-三十二节-FLXU原生态反推+controlnet depth(UNion)工作流-各个部分学习】
人工智能·学习
童话名剑1 小时前
锚框 与 完整YOLO示例(吴恩达深度学习笔记)
笔记·深度学习·yolo··anchor box
好奇龙猫2 小时前
【大学院-筆記試験練習:数据库(データベース問題訓練) と 软件工程(ソフトウェア)(7)】
学习
j_jiajia3 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
2301_783360133 小时前
关于RNAseq——从fastq到gene_counts全流程
笔记·学习
_李小白3 小时前
【AlohaMini学习笔记】第三天:AlohaMini相关技术
笔记·学习
我命由我123454 小时前
Photoshop - Photoshop 工具栏(57)模糊工具
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
yatingliu20194 小时前
将深度学习环境迁移至老旧系统| 个人学习笔记
笔记·深度学习·学习
week_泽4 小时前
第1课:AI Agent是什么 - 学习笔记_1
人工智能·笔记·学习