理解闭包
本课属于 Coddy Dart 学习旅程的“逻辑与流程控制”单元。第 46 课,共 65 课。
闭包是一种特殊的函数,即使创建它的原始上下文已经运行结束,它仍会“记住”创建位置的变量。你可以把它想象成一个无论走到哪里都会带着一部分诞生之地的函数。
当你在一个函数内部创建另一个函数时,内部函数可以访问外部函数的变量。闭包的特点是,即使外部函数执行完毕,这种访问权限仍然存在。
Function createGreeting(String name) {
return () {
return "Hello, $name!";
};
}在这个示例中,createGreeting 返回的匿名函数是一个闭包。它捕获了其外围作用域中的 name 参数。即使 createGreeting 运行结束后,返回的函数仍然记得 name 的值。
闭包非常适合用简洁的方式创建专用函数或维护状态。它们能让你根据函数创建时所处的环境来定制函数,使代码更加灵活、强大。
挑战
简单编写一个程序,通过构建个性化消息生成器系统来演示闭包。程序会创建能够“记住”特定信息的函数,并在原始上下文结束后,仍使用这些信息生成定制消息。
- 读取一个表示某人姓名的字符串输入
- 读取一个表示问候类型的字符串输入(
"formal"、"casual"或"friendly") - 读取一个表示公司名称的字符串输入
- 创建一个名为
createMessageGenerator的函数,该函数接收姓名和问候类型作为参数 createMessageGenerator函数应返回另一个函数(闭包),该函数:- 接收公司名称作为参数
- 使用外层函数作用域中的姓名和问候类型
- 根据问候类型返回格式化后的消息:
- 对于
"formal":"Dear [name], we are pleased to welcome you to [company]." - 对于
"casual":"Hey [name]! Welcome to [company]!" - 对于
"friendly":"Hi [name], so glad you joined [company]!" - 使用姓名和问候类型输入调用
createMessageGenerator函数,以获取闭包函数 - 使用公司名称输入调用返回的闭包函数来生成消息
- 按照下方所示的准确格式显示结果
例如,如果输入为 "Alice"、"formal" 和 "TechCorp",程序应输出:
Message Generator System
========================
Creating message generator for: Alice
Greeting type: formal
Company: TechCorp
========================
Generated message: Dear Alice, we are pleased to welcome you to TechCorp.
Message generation completed successfully如果输入为 "Bob"、"casual" 和 "StartupXYZ",程序应输出:
Message Generator System
========================
Creating message generator for: Bob
Greeting type: casual
Company: StartupXYZ
========================
Generated message: Hey Bob! Welcome to StartupXYZ!
Message generation completed successfully如果输入为 "Carol"、"friendly" 和 "InnovateLab",程序应输出:
Message Generator System
========================
Creating message generator for: Carol
Greeting type: friendly
Company: InnovateLab
========================
Generated message: Hi Carol, so glad you joined InnovateLab!
Message generation completed successfully程序必须通过创建一个返回另一个函数的函数来演示闭包。即使外层函数执行完毕,返回的函数(闭包)也应能访问外层函数作用域中的变量(姓名和问候类型)。使用条件语句,根据问候类型输入确定合适的消息格式。
亲手试试
import 'dart:io';
void main() {
// 读取输入
String? name = stdin.readLineSync();
String? greetingType = stdin.readLineSync();
String? company = stdin.readLineSync();
// 显示系统标题
print("Message Generator System");
print("========================");
print("Creating message generator for: $name");
print("Greeting type: $greetingType");
print("Company: $company");
print("========================");
// TODO:在下方编写代码
// 创建返回闭包的 createMessageGenerator 函数
// 调用函数并生成消息
// 输出最终结果
print("Generated message: \$message");
print("Message generation completed successfully");
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程控制中的所有课
自己练习: Dart 在线编译器