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



}
相关推荐
2025年一定要上岸7 小时前
【日常学习】10-15 学习re
学习·算法·正则表达式
koo3647 小时前
李宏毅机器学习笔记17
人工智能·笔记·机器学习
aramae7 小时前
数据结构与算法(递归)
开发语言·经验分享·笔记·算法
程序员大雄学编程7 小时前
「深度学习笔记1」深度学习全面解析:从基本概念到未来趋势
人工智能·笔记·深度学习
千码君20167 小时前
Go语言:记录一下Go语言系统学习的第一天
java·开发语言·学习·golang·gin·并发编程·编译语言
聪明的笨猪猪7 小时前
Java 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
学工科的皮皮志^_^7 小时前
电压源和电流源学习理解
单片机·嵌入式硬件·学习
骁的小小站8 小时前
Learn C the Hardway学习笔记和拓展知识(一)
c语言·开发语言·c++·经验分享·笔记·学习·bash
我命由我123458 小时前
PDFBox - PDDocument 与 byte 数组、PDF 加密
java·服务器·前端·后端·学习·java-ee·pdf
摇滚侠8 小时前
Spring Boot 3零基础教程,yml语法细节,笔记16
java·spring boot·笔记