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



}
相关推荐
不灭锦鲤1 小时前
网络安全学习第48天
学习
ALKAOUA2 小时前
力扣面试150题刷题分享
javascript·笔记
無限進步D2 小时前
Java 循环 高级(笔记)
java·笔记·入门
怪侠_岭南一只猿2 小时前
爬虫工程师入门阶段一:基础知识点完全学习文档
css·爬虫·python·学习·html
左左右右左右摇晃2 小时前
Spring + SpringMVC 面试题整理笔记(二)
笔记
今天你TLE了吗2 小时前
JVM学习笔记:第八章——执行引擎
java·jvm·笔记·后端·学习
左左右右左右摇晃3 小时前
Spring Boot + Vue 实现文件上传下载
笔记
蒙***团3 小时前
使用 MinMix 创建 Tailwindcss 学习网站全流程经验分享
学习
y = xⁿ3 小时前
【从零开始学习Redis|第四篇】从底层理解缓存问题:雪崩、击穿、穿透与一致性设计
java·redis·学习·缓存
在坚持一下我可没意见4 小时前
软件测试入门复习笔记:BUG篇
笔记·bug·测试