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



}
相关推荐
浮游本尊1 小时前
React 18.x 学习计划 - 第十四天:实战整合与进阶收尾
前端·学习·react.js
The_Uniform_C@t22 小时前
PWN | 对CTF WIKI的复现+再学习 (第八期)
网络·学习·网络安全·二进制
崎岖Qiu2 小时前
【计算机网络 | 第十三篇】网络层服务的两种实现方式:无连接和面向连接
网络·笔记·计算机网络
山岚的运维笔记2 小时前
SQL Server笔记 -- 第65章:迁移 第66章:表值参数
数据库·笔记·sql·microsoft·sqlserver
前路不黑暗@3 小时前
Java项目:Java脚手架项目的登录认证服务(十三)
java·spring boot·笔记·学习·spring·spring cloud·maven
前路不黑暗@4 小时前
Java项目:Java脚手架项目的 C 端用户服务(十五)
java·开发语言·spring boot·学习·spring cloud·maven·mybatis
Hello_Embed5 小时前
Modbus 传感器开发:STM32F030 libmodbus 移植
笔记·stm32·学习·freertos·modbus
知识分享小能手5 小时前
SQL Server 2019入门学习教程,从入门到精通,SQL Server 2019 视图操作 — 语法知识点及使用方法详解(16)
sql·学习·sqlserver
快乐zbc6 小时前
苍穹外卖 - 菜品起售/停售复习笔记
java·笔记