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



}
相关推荐
炽烈小老头4 小时前
【 每天学习一点算法 2026/04/12】x 的平方根
学习·算法
阿杰学AI5 小时前
AI核心知识115—大语言模型之 自监督学习(简洁且通俗易懂版)
人工智能·学习·ai·语言模型·aigc·监督学习·自监督学习
九英里路5 小时前
OS学习之路——动静态库制作与原理
linux·学习·操作系统·unix·进程·编译·动静态库
red_redemption6 小时前
自由学习记录(160)
学习
南無忘码至尊6 小时前
Unity学习90天-第2天-认识Unity生命周期函数并用 Update 控制物体移动,FixedUpdate 控制物理
学习·unity·游戏引擎
报错小能手7 小时前
ios开发方向——swift错误处理:do/try/catch、Result、throws
开发语言·学习·ios·swift
Z.风止7 小时前
Large Model-learning(3)
人工智能·笔记·后端·深度学习
LX567777 小时前
传统销售如何系统学习成为AI智能销售顾问?认证指南
人工智能·学习
做cv的小昊7 小时前
【TJU】应用统计学——第五周作业(3.1 假设检验的基本思想、3.2 单个正态总体参数的假设检验)
学习·线性代数·机器学习·数学建模·矩阵·概率论·tju
格鸰爱童话8 小时前
向AI学习项目技能(六)
java·人工智能·spring boot·python·学习