Typedefs (類型別名)
類型別名 (type alias) — 通常稱為 typedef,因為它是使用關鍵字 typedef
宣告的 — 是一種簡潔的方式來參照類型。以下是宣告和使用名為 IntList
的類型別名的範例
dart
typedef IntList = List<int>;
IntList il = [1, 2, 3];
類型別名可以有類型參數
dart
typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // Verbose.
ListMapper<String> m2 = {}; // Same thing but shorter and clearer.
我們建議在大多數情況下,使用inline function types (行內函式類型) 而不是 typedefs 作為函式。然而,函式 typedefs 仍然可能很有用
dart
typedef Compare<T> = int Function(T a, T b);
int sort(int a, int b) => a - b;
void main() {
assert(sort is Compare<int>); // True!
}
除非另有說明,否則本網站上的文件反映 Dart 3.7.1 版本。頁面最後更新於 2024-12-10。 檢視原始碼 或回報此頁面問題。