Dart 基础语法-泛型

1.可用于List,Set,Map

//List
var names = <String>['Seth', 'Kathy', 'Lars'];
//Set
var uniqueNames = <String>{'Seth', 'Kathy', 'Lars'};
//Map
var pages = <String, String>{
  'index.html': 'Homepage',
  'robots.txt': 'Hints for web robots',
  'humans.txt': 'We are people, not machines'
};

2.可用于方法

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;
}

3.泛型类

class Cache<T>{
  /// 缓存数据存储到该 Map 集合中
  Map<String, Object> _map = Map();

  /// 设置泛型缓存数据 , 该方法是泛型方法
  /// 此处将 T 类型的数据存放到 map 集合中
  void setCacheItem(String key, T value){
    _map[key] = value;
  }

  /// 取出泛型缓存数据 , 该方法是泛型方法
  T getCachedItem(String key){
    return _map[key];
  }
}

使用如下:

Cache<String> cache = Cache(); 
// 调用泛型方法时 , 传入的参数必须符合对应的泛型类型
// 泛型约束 : 泛型使用时会进行类型检查约束 , 如果设置错误的类型 , 编译时报错
cache.setCacheItem("name", "Tom");

// 获取缓存内容
String value = cache.getCachedItem("name");
print("泛型测试, 类型字符串, 获取的缓存内容为 ${value}");

// 创建泛型类对象 , 泛型类型设置为 int 类型
Cache<int> cache2 = Cache();
// 调用泛型方法时 , 传入的参数必须符合对应的泛型类型
// 泛型约束 : 泛型使用时会进行类型检查约束 , 如果设置错误的类型 , 编译时报错
cache2.setCacheItem("age", 18);

// 获取缓存内容
int value2 = cache2.getCachedItem("age");
print("泛型测试, 类型整型, 获取的缓存内容为 ${value2}");

输出结果:

I/flutter (24673): 泛型测试, 类型字符串, 获取的缓存内容为 Tom
I/flutter (24673): 泛型测试, 类型整型, 获取的缓存内容为 18
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容