Dart 基础6 --- 泛型

125 阅读1分钟
  • 泛型方法: 实现传入什么类型返回什么类型
T getData<T>(T value) {
   return value;
}

void main() {
  print(getData<int>(21)); // 21
}
  • 泛型类:
class MyList<T>{
   List list = <T>[];
   void add(T value) {
     this.list.add(value);
   }
   List getList(){
     return list;
   } 
 }

void main() {
 MyList l1 =  new MyList<String>();
  l1.add('zs');
  l1.add('ww');
  print(l1.getList());
}

  • 泛型接口
  1. 定义一个泛型接口,约束它的子类必须有getByKey和setBykey
  2. 要求setByKey时value的类型和实例化子类的时候指定的类型一致
 // 接口
abstract class Cache<T> {
  getByKey(String key);
  void setByKey(String key, T value);
}

// 实现接口
class FileCache<T> implements Cache<T> {
  @override
  getByKey(String key) {
    return key;
  }

  @override
  void setByKey(String key, T value) {
    print('${key} ==== ${value}');
  }
}

void main() {
  FileCache f = new FileCache<String>();
  f.setByKey('index', '首页数据');
}