泛型方法
T getData<T> (T val) {return val;}getData<String>('123');getData<int>(123);getData<double>(123);// getData<bool>(123); // Error: The argument type 'int' can't be assigned to the parameter type 'bool'.
泛型类
声明泛型类,比如声明一个 Array 类,实际上就是 List 的别名,而 List 本身也支持泛型的实现。
class Array<T> {List _list = new List<T>();Array();void add<T>(T value) {this._list.add(value);}get value{return this._list;}}Array arr = new Array<String>();arr.add('aa');arr.add('bb');// arr.add(123); // type 'int' is not a subtype of type 'String' of 'value'print(arr.value); // [aa, bb]Array arr2 = new Array<int>();arr2.add(1);arr2.add(2);print(arr2.value); // [1,2]
泛型接口
下面声明了一个 Storage 接口,然后 Cache 实现了接口,能够约束存储的 value 的类型:
abstract class Storage<T>{Map m = new Map();void set(String key, T value);void get(String key);}class Cache<T> implements Storage<T> {@overrideMap m = new Map();@overridevoid get(String key) {print(m[key]);}@overridevoid set(String key, T value) {print('set successed!');m[key] = value;}}print('----- 泛型接口 ------');Cache ch = new Cache<String>();ch.set('name', '123');// ch.set('name', 1232); // type 'int' is not a subtype of type 'String' of 'value'ch.get('name'); // String 123Cache ch2 = new Cache<Map>();// ch2.set('name', '23'); // type 'String' is not a subtype of type 'Map<dynamic, dynamic>' of 'value'ch2.set('ptbird', {'name': 'pt', 'age': 20});ch2.get('ptbird'); // {name: pt, age: 20}
