8.Generics 泛型(Dart中文文档)

  • 这篇翻译的很差

若是你看API文档中的数组篇,你会发现类型通常写成List .<...>的写法表示通用类型的数组(未明确指定数组中的数据类型)。一般状况泛型类型用E,T,S,K,V表示。 html

Why use generics? 为何用泛型

泛型是类型安全的(意思是你必须指定数据的类型),可是它的写法比硬编码指定类型高效的多:java

  • Properly specifying generic types results in better generated code.
  • 减小重复代码

若是你想让数组只有String值,定义为List 。这样,后续代码中,若是给数组赋值了非String类型,编译器将提示报错, web

var names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
names.add(42); // Error

另外一个使用泛型是缘由是为了减小重复代码。泛型让你经过一个单一类能够适配多种类型的数据操做,同时能够进行静态代码检查(好比,类型安全检查)。数组

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

上面代码是对Object类型操做,在没用泛型的状况下,你想对String类型操做,就得从新定义一个类安全

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

后面,你若是相对num类型操做,还得从新定义一个类。编码

而泛型就能够解决上面的问题,它经过对类型参数化,实现一个类针对多种数据类型操做的适配。翻译

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

Using collection literals 使用集合

List和map的字面量rest

List和map的字面量方式能够用指定类型参数。code

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

Using parameterized types with constructors 构造器中使用类型参数

var names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
var nameSet = Set<String>.from(names);

下面是map的泛型构造写法:htm

var views = Map<int, View>();

Generic collections and the types they contain

Dart的泛型类型是在运行时绑定的,这样,在运行时,能够知道List内具体类型。

var names = List<String>();
names.addAll(['Seth', 'Kathy', 'Lars']);
print(names is List<String>); // true

注意:java中,泛型是采用擦除的方式,它在运行时,其实对象都是Object类型或者泛型的约束父类。

Restricting the parameterized type

当泛型时,但愿限制参数的类型范围,能够用extends关键字约束。

class Foo<T extends SomeBaseClass> {
  // Implementation goes here...
  String toString() => "Instance of 'Foo<$T>'";
}

class Extender extends SomeBaseClass {...}

添加约束后,只要是指定的父类或者其子类均可以做为泛型参数。

var someBaseClassFoo = Foo<SomeBaseClass>();
var extenderFoo = Foo<Extender>();

也能够不指定泛型参数。

var foo = Foo();
print(foo); // Instance of 'Foo<SomeBaseClass>'

不能够用限定范围的泛型参数,这样静态代码检查器将提示错误。

var foo = Foo<Object>();

Using generic methods 泛型方法

Initially, Dart’s generic support was limited to classes. A newer syntax, called generic methods, allows type arguments on methods and functions:

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

下面是容许使用泛型方法的场景:

In the function’s return type (T).
In the type of an argument (List ). In the type of a local variable (T tmp).

相关文章
相关标签/搜索