元数据
使用元数据可以为代码增加一些额外的信息。元数据注解以 @ 开头,其后紧跟一个编译时常量(比如 deprecated)或者调用一个常量构造函数。
Dart 中有两个注解是所有代码都可以使用的: @deprecated、@Deprecated 和 @override。你可以查阅 扩展一个类 获取有关 @override 的使用示例。下面是使用 @deprecated 的示例:
class Television {
/// Use [turnOn] to turn the power on instead.
@Deprecated('Use turnOn instead')
void activate() {
turnOn();
}
/// Turns the TV's power on.
void turnOn() {...}
}
可以自定义元数据注解。下面的示例定义了一个带有两个参数的 @todo 注解:
library todo;
class Todo {
final String who;
final String what;
const Todo(this.who, this.what);
}
使用 @Todo 注解的示例:
import 'todo.dart';
@Todo('seth', 'make this do something')
void doSomething() {
print('do something');
}
元数据可以在 library、class、typedef、type parameter、 constructor、factory、function、field、parameter 或者 variable 声明之前使用,也可以在 import 或 export 之前使用。可使用反射在运行时获取元数据信息。