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



}
相关推荐
码界奇点3 分钟前
Java Web学习 第15篇jQuery万字长文详解从入门到实战解锁前端交互新境界
java·前端·学习·jquery
逐辰十七12 分钟前
EDA学习笔记
笔记·学习
MM_MS12 分钟前
VisionPro工具使用--->通过连接器距离及其角度的测量并显示案例掌握并学习到工具的知识点和使用步骤
学习·目标检测·计算机视觉·视觉检测
南龙大魔王14 分钟前
spring ai Alibaba(SAA)学习(二)
java·人工智能·spring boot·学习·ai
my_angle201616 分钟前
c语言 个人学习计划打卡与番茄钟程序
学习
代码游侠32 分钟前
应用——Linux进程编程实例分析
linux·运维·网络·笔记·学习·算法
大道之简37 分钟前
SpringAI入门学习
学习
在坚持一下我可没意见43 分钟前
Spring 开发小白学习过程中常用通用配置文件,即拿即用!(持续更新中)
java·数据库·后端·学习·spring·tomcat·mybatis
m0_6896182844 分钟前
这款微光学天线让机器人拥有“超灵敏多感官”,重量仅0.1克
网络·笔记·学习
He BianGu1 小时前
【笔记】在WPF App.cs中结合 IServiceCollection 进行 IOC 依赖注入
数据库·笔记·wpf