Dart-泛型

341 阅读1分钟

泛型定义

在 API 文档中你会发现基础数组类型 List 的实际类型是 List 。 <…> 符号将 List 标记为 泛型 (或 参数化) 类型。 这种类型具有形式化的参数。 通常情况下,使用一个字母来代表类型参数, 例如 E, T, S, K, 和 V 等。

使用泛型的原因

1.在 Dart 中类型是可选的,可以通过泛型来限定类型。
2.使用泛型可以有效地减少重复的代码。
3.泛型可以在多种类型之间定义同一个实现,同时还可以继续使用检查模式和静态分析工具提供的代码分析功能。
4.如果你需要更加安全的类型检查,则可以使用 参数化定义。

泛型函数

T getInfo<T> (T value){
    T num = value;
    return num;
}
void main(){
    T getInfo<T>(T value){
        return value;
    }

    // 参数和返回都是int类型
    var num = getInfo<int>(123);
    print(num);           // 123
    print(num is int);    // true

    // 参数和返回都是String类型
    var str = getInfo<String>("hello");
    print(str);             // hello
    print(str is String);   // true

    // 不指定类型
    var num1 = getInfo(123);
    print(num1);           // 123
    print(num1 is int);    // true
}

类泛型

class Person<T>{

    T sayhello(T value){
        print("hello,我是$value");
        return value;
    }
}

void main(){
    Person student = new Person<String>();
    var name = student.sayhello("小明");      // hello,我是小明
    print(name);                             // 小明
    print(name is String);                   // true
}

内置的泛型

dart中很多类都定义了泛型,例如List

void main(){
    // 未指定类型的List
    List list = List();
    list.add("小猫");
    list.add(123);
    print(list);  // [小猫, 123]

    // 限定List 泛型为String
    List list2 = List<String>();
    list2.add("小狗");
    list2.add(333);
    print(list2);  //报错: type 'int' is not a subtype of type 'String' of 'value'
}

限制泛型类型

使用extends 关键字来限定泛型参数的具体类型

class Person<T extends String>{
    T sayhello(T value){
        print("hello,我是$value");
        return value;
    }
}

void main(){
    Person student = new Person<String>();
    var name = student.sayhello("小明");  // hello,我是小明
    print(name);       // 小明
    print(name is String);    // true


    Person student2 = new Person<int>();
    var name2 = student2.sayhello(123);  // Type argument 'int' doesn't conform to the bound 'String' of the type variable 'T' on 'Person'.
    // print(name2);           // 123
    // print(name2 is int);    // true
}