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



}
相关推荐
U盘失踪了2 小时前
【笔记】Flask 用 session 对象存储用户状态
笔记
Brilliantwxx3 小时前
【C++】 vector(代码实现+坑点讲解)
开发语言·c++·笔记·算法
百锦再4 小时前
Auto.js变成基础知识学习
开发语言·javascript·学习·sqlite·kotlin·android studio·数据库开发
KuaCpp4 小时前
C++新特性学习
c++·学习
Komorebi_99997 小时前
大模型学习day5
学习·大模型
逍遥德7 小时前
AI时代,计算机专业大学生学习指南
java·javascript·人工智能·学习·ai编程
网络与设备以及操作系统学习使用者8 小时前
直连路由优先级最高
运维·网络·学习·华为·智能路由器
码途漫谈9 小时前
Easy-Vibe高级开发篇阅读笔记(五)——CC教程之Agent Teams
人工智能·笔记·ai·开源·ai编程
逆羽飘扬9 小时前
【AI Infra面试】基础学习汇总篇
人工智能·学习
憧憬成为原神糕手9 小时前
FFmpeg 音视频开发笔记(一):H.264 解码为 YUV
笔记·ffmpeg·音视频