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



}
相关推荐
幺零九零零6 小时前
压测学习-JMeter
学习·jmeter
lkbhua莱克瓦246 小时前
基础-函数
开发语言·数据库·笔记·sql·mysql·函数
程途拾光1587 小时前
自监督学习在无标签数据中的潜力释放
人工智能·学习
yuxb737 小时前
Kubernetes核心组件详解与实践:Service
笔记·kubernetes
软件技术NINI7 小时前
JavaScript性能优化实战指南
前端·css·学习·html
Blossom.1187 小时前
多模态大模型LoRA微调实战:从零构建企业级图文检索系统
人工智能·python·深度学习·学习·react.js·django·transformer
一 乐8 小时前
健身房预约|基于springboot + vue健身房预约小程序系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·小程序
sbc-study8 小时前
comsol学习-碱性电解槽堆中的分流-电化学,水解电槽,碱性
学习·comsol·电解槽·碱性·非局部耦合算子
wdfk_prog8 小时前
[Linux]学习笔记系列 -- [fs]kernfs
linux·笔记·学习
代码游侠8 小时前
学习笔记——IO多路复用技术
linux·运维·数据库·笔记·网络协议·学习