泛型

Catalogue   

泛型的好处

  • 适当地指定泛型可以更好地帮助代码生成。
  • 使用泛型可以减少代码重复。

使用集合字面量

List、Set 以及 Map 字面量也可以是参数化的。定义参数化的 List 只需在中括号前添加 ;定义参数化的 Map 只需要在大括号前添加 <keyType, valueType>:

1
2
3
4
5
6
7
var names = <String>['Seth', 'Kathy', 'Lars'];
var uniqueNames = <String>{'Seth', 'Kathy', 'Lars'};
var pages = <String, String>{
'index.html': 'Homepage',
'robots.txt': 'Hints for web robots',
'humans.txt': 'We are people, not machines'
};

使用类型参数化的构造函数

1
2
3
4
5
6
7
8
9
10

var nameSet = Set<String>.from(names);

var views = Map<int, View>();

//Dart的泛型类型是 固化的,这意味着即便在运行时也会保持类型信息
var names = <String>[];
names.addAll(['Seth', 'Kathy', 'Lars']);
print(names is List<String>); // true

限制参数化类型

1
2
3
4
class Foo<T extends Object> {
// Any type provided to Foo for T must be non-nullable.
}

泛型方法

1
2
3
4
5
6
7
8

T first<T>(List<T> ts) {
// Do some initial work or error checking, then...
T tmp = ts[0];
// Do some additional checking or processing...
return tmp;
}

方法 first 的泛型 T 可以在如下地方使用:

  • 函数的返回值类型 (T)。
  • 参数的类型 (List)。
  • 局部变量的类型 (T tmp)。