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



}
相关推荐
FserSuN17 小时前
AI编程 - 规范驱动开发(SDD)学习
驱动开发·学习·ai编程
2501_918126911 天前
stm32做一个次声波检测器,需要哪些元件
stm32·单片机·嵌入式硬件·学习·个人开发
GocNeverGiveUp1 天前
大模型学习2-Agent
学习
Bal炎魔1 天前
AI 学习专题一,AI 实现的原理
人工智能·学习
Ro Jace1 天前
分岔机制学习
人工智能·学习·机器学习
雾岛听蓝1 天前
C++11新特性(lambda、包装器)
c++·经验分享·笔记
反向跟单策略1 天前
期货反向跟单-2025年回顾及2026年展望
大数据·人工智能·学习·数据分析·区块链
yunhuibin1 天前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
xcLeigh1 天前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
知识分享小能手1 天前
PostgreSQL 入门学习教程,从入门到精通,PostgreSQL 16 语法知识点与案例详解(1)
数据库·学习·postgresql