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



}
相关推荐
淦。。。。几秒前
题解:P14013 [POCamp 2023] 送钱 / The Generous Traveler
开发语言·c++·经验分享·学习·其他·娱乐·新浪微博
GLDbalala3 分钟前
GPU PRO 4 - 5.1 An Aspect-Based Engine Architecture 笔记
笔记
小裕哥略帅7 分钟前
PMP学习笔记--过程
笔记·学习
好奇龙猫16 分钟前
【人工智能学习-AI入试相关题目练习-第六次】
人工智能·学习
ocean'22 分钟前
渗透笔记总结
笔记
ljt272496066132 分钟前
Flutter笔记--Isolate
笔记·flutter
[H*]35 分钟前
鸿蒙跨端Flutter学习:InheritedWidget嵌套使用
学习·flutter
weixin_4407305037 分钟前
02测试基础知识笔记
笔记
2501_9418649637 分钟前
科学记忆法提升学习效率
学习
就叫飞六吧38 分钟前
Jenkins 流水线全流程实战笔记
笔记·servlet·jenkins