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



}
相关推荐
解局易否结局32 分钟前
昇腾CANN上手笔记:从cann-learning-hub学会ops-transformer
笔记·深度学习·transformer
吃好睡好便好6 小时前
用while循环语句求和
开发语言·学习·算法·matlab·信息可视化
摇滚侠6 小时前
Java 零基础全套教程,集合框架,笔记 153-163
java·开发语言·笔记
ゆづき7 小时前
计算机数据存储全解:从底层进制转换到存储介质演进
笔记·学习·生活
小+不通文墨7 小时前
树莓派玩转EMQX的常用指令清单
经验分享·笔记·学习
kdxiaojie8 小时前
U-Boot分析【学习笔记】(12)
linux·笔记·学习
吃好睡好便好8 小时前
用for循环语句求和
开发语言·人工智能·学习·matlab·学习方法
玄米乌龙茶1239 小时前
LLM成长笔记(五):提示词工程与模型调用
人工智能·笔记
不会编程的懒洋洋9 小时前
VisionPro 中 几何相交工具 Geometry-Intersection
图像处理·笔记·c#·视觉检测·机器视觉·visionpro
_李小白9 小时前
【C++学习笔记】新特性之inline变量
c++·笔记·学习