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



}
相关推荐
HyperAI超神经7 小时前
IQuest-Coder-V1:基于代码流训练的编程逻辑增强模型;Human Face Emotions:基于多标注维度的人脸情绪识别数据集
人工智能·深度学习·学习·机器学习·ai编程
testpassportcn8 小时前
UiPath-ADPV1 認證介紹|Automation Developer Professional v1
网络·学习·改行学it
生擒小朵拉8 小时前
ROS1学习笔记(二)
笔记·学习
Root_Hacker8 小时前
include文件包含个人笔记及c底层调试
android·linux·服务器·c语言·笔记·安全·php
Gorgous—l10 小时前
数据结构算法学习:LeetCode热题100-动态规划篇(下)(单词拆分、最长递增子序列、乘积最大子数组、分割等和子集、最长有效括号)
数据结构·学习·算法
窗边鸟11 小时前
小白日记之java方法(java复习)
java·学习
burning_maple12 小时前
redis笔记
数据库·redis·笔记
魔芋红茶12 小时前
Spring Security 学习笔记 4:用户/密码认证
笔记·学习·spring
googleccsdn12 小时前
ENSP Pro Lab笔记:配置BGP VXLAN双栈(3)
网络·笔记
爱宁~12 小时前
UnityShader学习笔记[二百九十九]UGUI中的Mask遮罩半透明Shader
笔记·学习