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



}
相关推荐
Xudde.1 天前
班级作业笔记报告0x04
笔记·学习·安全·web安全·php
晓晓hh1 天前
JavaSE学习——迭代器
java·开发语言·学习
421!1 天前
GPIO工作原理以及核心
开发语言·单片机·嵌入式硬件·学习
AI成长日志1 天前
【笔面试算法学习专栏】双指针专题·简单难度两题精讲:167.两数之和II、283.移动零
学习·算法·面试
zzh0811 天前
MySQL高可用集群笔记
数据库·笔记·mysql
小手指动起来1 天前
保姆级提示词工程学习总结(含实操示例+工具推荐)
人工智能·学习·自然语言处理
绛橘色的日落(。・∀・)ノ1 天前
Matplotlib实践学习笔记
笔记·学习
chase。1 天前
【学习笔记】AGILE:把人形机器人强化学习从“玄学”变成“工程学”
笔记·学习·敏捷流程
久菜盒子工作室1 天前
高等教育学|第一章高等教育概述
经验分享·笔记·课程设计
bu_shuo1 天前
git练习学习网站【中文网站】
git·学习