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



}
相关推荐
hmbbcsm2 小时前
关于transformors库的学习笔记
笔记·学习
xqqxqxxq2 小时前
Java AI智能P图工具技术笔记
java·人工智能·笔记
FakeOccupational3 小时前
【电路笔记 PCB】Altium Designer : AD20信号完整性(Signal Integrity)分析+单线路传输分析+串扰分析(暂记)
笔记
minglie13 小时前
qemu相关脚本
学习
闪闪发亮的小星星4 小时前
链路预算相关
笔记
霍霍的袁5 小时前
【初识C语言】预处理笔记(预处理指令、宏定义等)
c语言·笔记·visualstudio
@小博的博客5 小时前
CSDN年度技术趋势预测的技术
学习
可可西里_X_back6 小时前
Linux学习(二)- 驱动开发步骤
linux·驱动开发·学习
dr_yingli6 小时前
慢性肾脏病评估与管理临床实践指南 KDIGO 2024 CKD 诊断指标速查手册
笔记
GISer_Jing6 小时前
测绘与GIS考试高频考点选择题精选
学习·arcgis