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



}
相关推荐
Lhan.zzZ30 分钟前
笔记_2026.4.28_004
c++·ide·笔记·qt
其实防守也摸鱼3 小时前
CTF密码学综合教学指南--第五章
开发语言·网络·笔记·python·安全·网络安全·密码学
网络工程小王3 小时前
【LangChain 大模型6大调用指南】调用大模型篇
linux·运维·服务器·人工智能·学习
qq_571099353 小时前
学习周报四十三
学习
小郑加油4 小时前
python学习Day12:pandas安装与实际运用
开发语言·python·学习
Yeh2020585 小时前
Filter与Listener笔记
笔记
九成宫5 小时前
Git 与远程仓库实操记录:克隆、配置、分支推送与问题排查
笔记·git·ssh
MegaDataFlowers6 小时前
英语六级我还在背单词:Unit 1(Lesson 2)
学习
东京老树根6 小时前
SAP学习笔记 - BTP SAP Build12 - SAP Build Content Package
笔记·学习
北京海得康6 小时前
阿那格雷临床疗效与起效时间【海得康】
笔记