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



}
相关推荐
wjykp2 小时前
part5 dl的学习技巧
学习
weixin_433179333 小时前
《旋元佑进阶文法》之 副词
笔记·英语语法
hssfscv3 小时前
JavaWeb学习笔记——后端实战1_准备工作
笔记·后端·学习
JavaLearnerZGQ3 小时前
redis笔记大全
数据库·redis·笔记
hellodaoyan3 小时前
网络技术学习交换机原理作用让多台电脑通信
学习
运维管理3 小时前
h3c DHCP-学习篇
学习
好奇龙猫4 小时前
【人工智能学习-AI-MIT公开课-第9.约束:视觉对象识别(視覚対象認識)】
学习
程序猿零零漆5 小时前
Spring之旅 - 记录学习 Spring 框架的过程和经验(八)基于Spring的注解应用
java·学习·spring
·present·5 小时前
射频网课学习第二章(阻抗匹配 ch2-5到ch2-9部分)
学习
航Hang*5 小时前
第五章:综合布线技术 —— 管理间(电信间)设计与施工
网络·笔记·学习·设计·光纤