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



}
相关推荐
志尊宝7 分钟前
Vue3 零基础每日笔记(052):路由常见坑一次排雷——404、刷新丢参数、部署白屏
前端·javascript·vue.js·笔记·html5
05664622 分钟前
用大模型构建答疑机器人:从 API 调用到上下文工程
python·学习·agent
我爱cope26 分钟前
【操作系统 | 开篇:什么是操作系统?从裸机到多任务系统】
学习·操作系统
Ztt6666666661 小时前
一抹霞红停在圆肩壶上,留白让颜色更醒目
经验分享·笔记·其他·百度·微信公众平台
迪丽热爱1 小时前
多媒体应用18-901(补)
学习
摇滚侠2 小时前
《Spring Boot 3:高级与架构设计》第 2 章 IOC容器的高级机制 Environment 个人理解 4
java·spring boot·笔记·后端
传奇开心果编程2 小时前
【Rust入门练中学】第4课:函数与所有权入门
开发语言·学习·rust
Demons_kirit2 小时前
cookie的samesite机制
笔记·note
那个松鼠很眼熟w2 小时前
填充word文档【Apache POI】
笔记
从零开始的嵌入式之旅2 小时前
day46
linux·arm开发·笔记·嵌入式硬件