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();
        }
    }



}
相关推荐
云深处@9 小时前
【数据库】MySQL 入门
数据库·学习·mysql
果果燕9 小时前
实习笔记(一):NFS、Samba、VNC、Git、CMake、systemd、内核、交叉编译
linux·arm开发·c++·笔记·git
HyperAI超神经9 小时前
【vLLM 学习】Disaggregated Prefill
人工智能·深度学习·学习·vllm
天吾cc9 小时前
RTT-IO设备模型
单片机·嵌入式硬件·学习
美味蛋炒饭.9 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
呼噜想睡觉10 小时前
Bootstrap 组件之响应式导航条实现
学习
菜鸟‍10 小时前
【论文学习】Medical Image Analysis 2024 || 医学图像分割中失败检测方法的比较基准研究:揭示置信度聚合的作用
人工智能·学习
Zguigo11 小时前
第25-26讲:计算机操作系统存储管理——分页机制、页表与快表(TLB)
linux·windows·笔记
爱音乐的marlon11 小时前
FastAPI 学习笔记03|core 核心层:config 是总控制台,database 是整个工程的地基
笔记·学习·fastapi
math_hongfan13 小时前
鸿蒙离线数据缓存高级架构:弱网预加载/离线数据优先级/同步冲突解决/上线后数据合并策略
学习·缓存·华为·架构·harmonyos·鸿蒙