元數(shù)據(jù)

2020-02-03 23:47 更新

使用元數(shù)據(jù)可以提供有關(guān)代碼的其他信息。 元數(shù)據(jù)注釋以字符 @ 開頭, 后跟對編譯時常量 (如 deprecated) 的引用或?qū)ΤA繕?gòu)造函數(shù)的調(diào)用。

對于所有 Dart 代碼有兩種可用注解:@deprecated 和 @override。 關(guān)于 @override 的使用, 參考 擴(kuò)展類(繼承)。 下面是使用 @deprecated 注解的示例:

class Television {
  /// _Deprecated: Use [turnOn] instead._
  @deprecated
  void activate() {
    turnOn();
  }

  /// Turns the TV's power on.
  void turnOn() {...}
}

可以自定義元數(shù)據(jù)注解。 下面的示例定義了一個帶有兩個參數(shù)的 @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');
}

元數(shù)據(jù)可以在 library、 class、 typedef、 type parameter、 constructor、 factory、 function、 field、 parameter 或者 variable 聲明之前使用,也可以在 import 或者 export 指令之前使用。 使用反射可以在運(yùn)行時獲取元數(shù)據(jù)信息。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號