Flutter Dart 泛型

55 阅读1分钟

泛型(宽泛的数据类型)

尖括号 <> 常用字母 E T S K V 常用于设计架构

image.png

T getData<T>(T value){
    reutrn value
}
void main(List<String> args) { 
    print(getData<int>(12));
    
    print(getData<String>("hello"));
}

泛型函数

// //1、固定类型
// int getData(int value){
//   return value;
// }

// //2、动态类型,不指定类型,
// getData(value){
//   return value;
// }

// //3、泛型类型
// T getData<T>(T value){
//   return value;
// }


// //4、多个泛型类型
// E getData<T,E>(T value){
//   return value as E;
// }

//5、只约束输入类型
getData<T>(T value){
  return value;
}

void main(List<String> args) {
  print(getData<String>("20"));
}

泛型类


class CommonClass {
  Set s = Set<int>();

  void addElement(int v) {
    this.s.add(v);
  }

  void info() {
    print(this.s);
  }
}

//泛型类
class GenericClass<T> {
  Set s = Set<T>();

  void addElement(T v) {
    this.s.add(v);
  }

  void info() {
    print(this.s);
  }
}

void main(List<String> args) {
  CommonClass c = CommonClass();
  c.addElement(20);
  c.info();

  GenericClass g = GenericClass<int>();
  g.addElement(10);
  g.addElement(20);
  g.info();

  GenericClass g1 = GenericClass<String>();
  g1.addElement("10");
  g1.addElement("20");
  g1.info();
}

泛型接口


import 'dart:typed_data';

abstract class ObjectCache {
  getByKey(String key);
  void setByKey(String key, Object value);
}

abstract class Cache<T> {
  getByKey(String key);
  void setByKey(String key, T value);
}

class BaseClass {}

class FileCache<T extends BaseClass> implements Cache<T> {
  @override
  getByKey(String key) {
    return null;
  }

  @override
  void setByKey(String key, T value) {
    print("文件缓存 key = $key value = $value");
  }
}

class MemoryCache<T> implements Cache<T> {
  @override
  getByKey(String key) {
    return null;
  }

  @override
  void setByKey(String key, T value) {
    print("内存缓存 key = $key value = $value");
  }
}

void main(List<String> args) {
  FileCache fileCache = FileCache();
  print(fileCache);
  FileCache fileCache1 = FileCache<BaseClass>();
  print(fileCache1);

  MemoryCache memoryCache = MemoryCache<BytesBuilder>();
  final bb = BytesBuilder();
  bb.addByte(10);
  memoryCache.setByKey("fileKey", bb);
}