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 小时前
godot2D游戏教程系列二(4)
笔记·学习·游戏开发
BORN(^-^)1 小时前
《产品经理方法论》阅读笔记
笔记·产品经理
jrlong2 小时前
DataWhale大模型基础与量化微调task4学习笔记(第 2 章:高级微调技术_RLHF 技术详解)
笔记·学习
Darkershadow2 小时前
蓝牙学习之Time Set
python·学习·蓝牙·ble·mesh
傻小胖2 小时前
13.BTC-思考-北大肖臻老师客堂笔记
笔记·区块链
好奇龙猫2 小时前
【日语学习-日语知识点小记-日本語体系構造-JLPT-N2前期阶段-第一阶段(9):単語文法】
学习
AI浩2 小时前
约束模型下的目标检测置信学习
学习·目标检测·目标跟踪
m0_748229993 小时前
ThinkPHP快速入门:从零到实战
c语言·开发语言·数据库·学习
風清掦3 小时前
【江科大STM32学习笔记-04】0.96寸OLED显示屏
笔记·stm32·学习
胡西风_foxww3 小时前
ObsidianAI_学习一个陌生知识领域_建立学习路径和知识库框架_写一本书
人工智能·笔记·学习·知识库·obsidian·notebooklm·写一本书