> Dart中文手册 > Dart 注释

注释

在说明成员以及类型的时候应该使用 doc 注释。

尽管 Dart 支持两种类型的 doc 注释(/// 以及 /**),我们推荐 ///,因为它更加紧凑(/** 以及 */ 用于多行注释,并且有两行是空的)。在有些情况下,/// 也更加容易阅读,比如在某个 doc 注释中包含了一个列表,并且该列表使用 * 来标记各个列表项。

// good
/// Parses a set of option strings.
///
/// For each option:
///
/// * If it is `null`, then it is ignored.
/// * If it is a string, then [validate] is called on it.
/// * If it is any other type, it is *not* validated.
void parse(List options) {
  // ...
}

在 doc 注释中,你可以使用 markdown 格式。

应该使用单行注释。

// good
greet(name) {
  // Assume we have a valid name.
  print('Hi, $name!');
}
// bad
greet(name) {
  /* Assume we have a valid name. */
  print('Hi, $name!');
}

你可以使用块注释(/* ... */)来在某段代码之外进行注释。

注释也应该像普通句子一样大小写并且添加标点。

这并不是说注释就应该是一个完整的句子,尽管多数情况下它应该是一个完整的句子。“返回条目的数量”就是一个可接受的注释。

// good
// Remove the last item from the collection.
// bad
// remove the last item from the collection

在注释中应该使用方括号把相应域中的标识符标记出来。

如果你把变量、方法或者类型的名称放在方括号内,那么文档生成器就可以查找到相应的名称,并且将其与代码连接起来。

// good
import 'dart:math';

/// Rolls both [Dice] and returns the highest rolled value.
num greatestRoll(Dice a, Dice b) => max(a.roll(), b.roll());

//

在文档注释中应该描述函数签名。

在其他语言中,要使用很多的标签以及各个部分来说明函数的参数是什么,返回值又是什么。

//bad
/// Defines a flag with the given name and abbreviation.
///
/// @param name The name of the flag.
/// @param abbr The abbreviation for the flag.
/// @returns The new flag.
/// @throws IllegalArgumentException If there is already an option with
///     the given name or abbreviation.
Flag addFlag(String name, String abbr) {
  // ...
}

使用 Dart 则相当便捷,你可以直接使用方括号把参数等信息整合到函数描述中。

// good
/// Defines a flag.
///
/// Throws an [IllegalArgumentException] if there is already an option named
/// [name] or there is already an option using abbreviation [abbr]. Returns
/// the new flag.
Flag addFlag(String name, String abbr) {
  // ...
}

注释应该放在元数据注解之前。

// good
/// _Deprecated: Use [newMethod] instead._
@deprecated
oldMethod();
// bad
@deprecated
/// _Deprecated: Use [newMethod] instead._
oldMethod();
上一篇:
下一篇: