- 通过泛型限制变量类型
dart
List<String> list = ['java', 'c++', 'python', 'javascript', 'dart'];
- 函数泛型
dart
V test<K, V>(K key, V val) {
print('$key => $val');
return val;
}
var name = test('name', '煎蛋');
print(name);
- 构造函数泛型
dart
class Mobile<T> {
final T number;
Mobile(this.number);
}
var p = Mobile('110');
print(p.number);
var m = Mobile(120);
print(m.number);
- 通过泛型限制实例类型
dart
class Mobile {
void powerOn() {
print('开机...');
}
}
class Android<T extends Mobile> {
final T mobile;
Android(this.mobile);
}
var m = Mobile();
var p = Android<Mobile>(m);
p.mobile.powerOn();