C#练习题——Lambad表达式的应用
一、任务
(1)有一个函数,会返回一个委托函数
(2)这个委托函数中只有一句打印代码
(3)之后执行返回的委托函数时,可以打印出1~10
二、重点知识点讲解
1. 闭包陷阱与解决方案
问题:直接捕获循环变量 i
// ❌ 错误写法:所有委托都捕获同一个i的引用
a += () => { Console.WriteLine(i); };
// 输出结果:11, 11, 11... (全部是最终值)
解决方案:创建局部副本
// ✅ 正确写法:每个委托捕获独立的index
int index = i; // 每次循环创建新变量
a += () => { Console.WriteLine(index); };
// 输出结果:1, 2, 3...10 (正确的序列值)
2. 委托链构建
Action a = null;
a += () => { /* 方法1 */ };
a += () => { /* 方法2 */ };
// 📌 a现在包含两个方法,按添加顺序执行
3. 执行方式
PrintNum()(); // 双括号语法
// 第一个(): 调用方法,返回委托
// 第二个(): 执行返回的委托链
三、完整代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;namespace 进阶测试
{class Program{public static Action PrintNum(){Action a = null;for (int i = 1;i<11;i++){int index = i;a +=() =>{Console.WriteLine(index);};}return a;}static void Main(string[] args){PrintNum()();}}
}