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



}
相关推荐
YM52e3 小时前
鸿蒙Flutter Padding内边距:EdgeInsets详解
android·学习·flutter·华为·harmonyos·鸿蒙
摇滚侠4 小时前
AI 编程工具 《TRAE 官方手册》阅读笔记 AI 编程核心 上
人工智能·笔记
西安老张(AIGC&ComfyUI)6 小时前
第034章:ComfyUI&AIGC一阶段学习总结及下阶段学习安排
学习·aigc
正经人_x8 小时前
学习日记43:FINO
学习
Ztt6666666669 小时前
六方壶不只看棱角,转得温和才耐看
经验分享·笔记·其他·百度·微信公众平台
网络工程小王10 小时前
【HCIE-AI】11.模型 昇腾迁移适配-精度调试-性能调优
人工智能·学习·华为·迁移学习·昇腾
RainCity11 小时前
Java Swing 自定义组件库分享(十五)
java·笔记·后端
一只小菜鸡..11 小时前
CMU 15-213 CSAPP:机器级编程与内存的暗黑魔法(Machine-Level)
笔记·学习
ysa05103012 小时前
【板子】二分答案(最大最小?)
c++·笔记·算法·板子
吃好睡好便好14 小时前
近期几点体会
学习·生活