注释
Dart支持单行注释、多行注释和文档注释。
单行注释
#单行注释以 // 开头。Dart 编译器会忽略 // 之后直到行末的所有内容。
dart
void main() {
// TODO: refactor into an AbstractLlamaGreetingFactory?
print('Welcome to my Llama farm!');
}
多行注释
#
多行注释以 /* 开头,以 */ 结尾。
Dart 编译器会忽略 /* 和 */ 之间的所有内容(除非该注释是文档注释;请参阅下一节)。多行注释可以嵌套。
dart
void main() {
/*
* This is a lot of work. Consider raising chickens.
Llama larry = Llama();
larry.feed();
larry.exercise();
larry.clean();
*/
}
文档注释
#
文档注释是以 /// 或 /** 开头的多行或单行注释。连续多行使用 /// 的注释效果与多行文档注释等效。
在文档注释中,分析器会处理被方括号括起来的文本内容。通过使用方括号,你可以引用类、方法、字段、顶层变量、函数和参数。方括号中的名称将根据注释对象的词法作用域 (Lexical Scope) 进行解析。
以下是一个包含对其他类和参数引用的文档注释示例:
dart
/// A domesticated South American camelid (Lama glama).
///
/// Andean cultures have used llamas as meat and pack
/// animals since pre-Hispanic times.
///
/// Just like any other animal, llamas need to eat,
/// so don't forget to [feed] them some [Food].
class Llama {
String? name;
/// Feeds your llama [food].
///
/// The typical llama eats one bale of hay per week.
void feed(Food food) {
// ...
}
/// Exercises your llama with an [activity] for
/// [timeLimit] minutes.
void exercise(Activity activity, int timeLimit) {
// ...
}
}
在生成的类文档中,
[feed] 会转换为指向 feed 方法文档的链接,而 [Food] 则会转换为指向 Food 类文档的链接。
如果你需要解析 Dart 代码并生成 HTML 文档,你可以使用 Dart 的文档生成工具 dart doc。关于生成的文档示例,请参阅 Dart API 文档。关于代码注释规范的建议,请参阅 高效 Dart 语言指南:文档。