Android学Dart学习笔记第八节 Typedefs 别名
文章摘要:本文介绍了Dart语言中的类型别名(typedef)功能及其应用场景。类型别名通过typedef关键字创建,为复杂类型提供简洁引用方式。文章展示了基本用法(如typedef IntList = List<int>)、带泛型参数的类型别名,并指出2.13版本后扩展了非函数类型的支持。特别探讨了typedef在记录类型(Record)中的实用价值,如组合多个数据类(typedef
A type alias—often called a typedef because it’s declared with the keyword typedef—is a concise way to refer to a type
译文:类型别名(通常称为typedef,因为用typedef关键字声明)是引用类型的一种简洁方式
Here’s an example of declaring and using a type alias named IntList
译文:下面的例子声明并使用了名为IntList的类型别名
typedef IntList = List<int>;
IntList il = [1, 2, 3];
下面是我自己的一个例子:
typedef A = People;
void main() {
A p = new A('张三', 18);
print(p.name);//张三
}
class People() {
String name;
int age;
constructor(this.name, this.age);
}
十分的离谱,我给People起了个毫不相关的名字,A,之后A就是People的代称,怎么说呢。有好处也有坏处吧。
A type alias can have type parameters:
译文:类型别名可以有类型参数:
typedef ListMapper<X> = Map<X, List<X>>;
Map<String, List<String>> m1 = {}; // Verbose.
ListMapper<String> m2 = {}; // Same thing but shorter and clearer.
很神奇,我有一个启发。之前写代码看到不认识的类可能是自己没用过的,需要深入了解下,现在有可能是包装了一层的名字。
提示 Before 2.13, typedefs were restricted to function types. Using the new typedefs requires a language version of at least 2.13.
在2.13之前,typedefs仅限于函数类型。使用新的typedefs需要至少2.13的语言版本。
We recommend using inline function types instead of typedefs for functions, in most situations. However, function typedefs can still be useful:
译文:在大多数情况下,我们建议使用内联函数类型,而不是函数的typedefs。
然而,函数typedefs仍然可以很有用:
typedef Compare<T> = int Function(T a, T b);
int sort(int a, int b) => a - b;
void main() {
assert(sort is Compare<int>); // True!
}
官方这个例子我暂时想不出实际的使用场景。相对于之前的语言是一种新的东西。
不过我们也学到typedef可以用来描述一种函数格式。
接下来搞一下前情回顾吧,之前在学习Record时我们也提到了typedef,在当时是一个非常有用的东西,我们一起回顾下。
在我们实际开发中,我们常常在一个列表中,并不只依赖一个接口数据,需要我们对数据做一些合并,比如用户详情,下面是例子
class User{
String id;
String name;
int age;
constructor(this.id, this.name, this.age);
}
class UserMore {
String tel;
String address;
constructor(this.tel, this.address);
}
var user = User("10000", "张三", 18);//假设这个是前面列表拿到的简单数据
var userMore = UserMore("13800000000", "北京市海淀区");//这个是详情页拿到的补充数据,且只有我们这里会显示
typedef DetailInfo = (User, UserMore);//定义一个记录类型,包含用户基本信息和补充信息
var detailInfo = DetailInfo(user, userMore);//创建一个记录实例,包含用户基本信息和补充信息
detailInfo.user.name;//张三
detailInfo.userMore.tel;//13800000000
这样的话,我们在数据的传递和使用中就可以直接使用DetailInfo,而无需对前面User对象做补充。它可以像一个正常的bean类一样使用。
顺带提一句,在dart中要注意括号的使用,不熟悉的时候会比较容易搞混。
给大家出个题加深下记忆,下面的代码中定义了一种什么类型
typedef test = {User, UserMore};
var testIns = test({user, userMore});
告辞!
更多推荐



所有评论(0)