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



}
相关推荐
小冷coding1 分钟前
复杂场景下的ERP系统优化策略:让企业管理系统焕发新生
笔记
随意起个昵称5 分钟前
【二分做题笔记】组装玩具
笔记·算法
Lips6115 分钟前
2026.1.13力扣刷题笔记
笔记·算法·leetcode
deng-c-f5 分钟前
Linux C/C++ 学习日记(62):Redis(三):订阅
数据库·redis·学习
L16247610 分钟前
Prometheus、Cadvisor和Grafana体系完整学习手册
学习·grafana·prometheus
Silvia_suu28 分钟前
修电脑的笔记
笔记
望云山19033 分钟前
ESP32—S3学习--入门五个基础实验
嵌入式硬件·学习
renhongxia136 分钟前
学习基于数字孪生的质量预测与控制
人工智能·深度学习·学习·语言模型·自然语言处理·制造
koo36438 分钟前
pytorch深度学习笔记16
pytorch·笔记·深度学习
开开心心_Every40 分钟前
重复图片智能清理工具:快速查重批量删除
java·服务器·开发语言·前端·学习·edge·powerpoint