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



}
相关推荐
kaixin_啊啊2 小时前
【DNA数据学习】从DNA序列到模型预测
学习·生物信息
嘉泰姆半导体官方3 小时前
固定5V输出的非隔离AC-DC芯片选型与电路设计笔记(CXAC85369)
笔记
软件技术NINI4 小时前
基于 Spring Boot 中国历史知识学习系统
spring boot·后端·学习
iiiiii114 小时前
从最大熵到 SAC:Soft Q-Learning 与 Soft Actor-Critic 公式推导笔记
人工智能·笔记·算法·机器学习·强化学习
Uio2416 小时前
Java 泛型详解:为什么要用泛型?实战+避坑(CSDN)
笔记
源码手记7 小时前
基于微信小程序的驾考刷题学习系统-毕设源码
学习·微信小程序·课程设计
小李不想当小白7 小时前
HAL库之定时器输出比较(STM32 HAL库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式
sharemylove17 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
whyTeaFo17 小时前
GAMES202: Lecture 3: Real-Time Shadows 1 ppt笔记
笔记
摇滚侠19 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 20
java·笔记·python