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



}
相关推荐
航Hang*11 分钟前
计算机等级考试(二级WPS)---第1章:综合应用基础---第2节:PDF文件应用
笔记·学习·pdf·wps·计算机二级·计算机等级考试
zhangrelay14 分钟前
Linux(ubuntu)如何锁定cpu频率工作在最低能耗模式下
linux·笔记·学习
三伏52221 分钟前
Cortex-M3权威指南Cn第四、五章——笔记
笔记·cortex-m3
老神在在00128 分钟前
Token身份验证完整流程
java·前端·后端·学习·java-ee
轴测君1 小时前
MobileNet V1
人工智能·pytorch·笔记
ValidationExpression1 小时前
学习:词嵌入(Word Embedding / Text Embedding)技术
python·学习·ai
Aliex_git1 小时前
Claude Code 使用笔记(一)- 配置和基础
人工智能·笔记·学习·ai编程
云潮汐表1 小时前
烟台潮汐表查询2026-01-25
笔记
电饭叔2 小时前
定义中的【谓词】是什么
学习
万变不离其宗_82 小时前
DBeaver 使用笔记
笔记