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



}
相关推荐
longxiangam4 小时前
esp-idf 中 mipi dsi 使用的笔记
笔记
喜欢踢足球的老罗4 小时前
从移动开发转型 AI Agent 工程师:我做了一个开源学习系统
人工智能·学习
EntyIU4 小时前
JVM内存与GC笔记
java·jvm·笔记
wuxinyan1234 小时前
工业级大模型学习之路030:Streamlit 企业级智能体前端工作台
前端·学习·streamlit·智能体
长安紫薯5 小时前
学习AI日记
学习
星恒随风5 小时前
C语言数据结构排序算法详解(下):冒泡排序、快速排序、归并排序和计数排序
c语言·数据结构·笔记·学习·排序算法
NagatoYukee6 小时前
Spring Security基础部分学习
java·学习·spring
米小葱6 小时前
【学习笔记】cmake
笔记·学习
辰海Coding7 小时前
MiniSpring框架学习-分解 Dispatcher
java·学习·spring·架构
初夏睡觉7 小时前
数据结构学习之~二叉堆 (P3378 【模版】堆)
数据结构·c++·学习