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



}
相关推荐
QT 小鲜肉18 小时前
【C++基础与提高】第一章:走进C++的世界——从零开始的编程之旅
开发语言·c++·笔记·qt
老虎062718 小时前
黑马点评学习笔记10(优惠券秒杀下单优化(分布式锁的优化,Lua脚本))
笔记·分布式·学习
递归不收敛18 小时前
config.json 完全指南:项目配置的核心实践
笔记·学习·json
shenghaide_jiahu18 小时前
字符串匹配和回文串类题目
学习·算法·动态规划
一个平凡而乐于分享的小比特19 小时前
UCOS-III笔记(一)
笔记·ucosiii
驯狼小羊羔19 小时前
学习随笔-http和https有何区别
前端·javascript·学习·http·https
风无雨19 小时前
gin学习
学习·gin
lkbhua莱克瓦2419 小时前
Java入门——Java跨平台的原理
java·开发语言·笔记·github
皓木.19 小时前
软件测试-app测试
笔记
招风的黑耳20 小时前
Axure可视化大屏原型模板库:学习设计/提高效率/快速可视化
学习·axure·数据可视化·大屏设计