1、概 述
本文是在鸿蒙多线程开发——线程间数据通信对象03(sendable)基础上做的扩展讨论。
Sendable协议定义了ArkTS的可共享对象体系及其规格约束。符合Sendable协议的数据(以下简称Sendable对象)可以在ArkTS并发实例间传递。
默认情况下,Sendable数据在ArkTS并发实例间(包括主线程、TaskPool、Worker线程)传递的行为是引用传递。同时,ArkTS也支持Sendable数据在ArkTS并发实例间拷贝传递。
Sendable的使用有一些需要注意的事项,本文针对较常见的情况做讨论。
2、Sendable的使用规则与约束
主要规则有:
-
Sendable class只能继承自Sendable class;
-
非Sendable class只能继承自非Sendable class;
-
非Sendable class只能实现非Sendable interface;
-
Sendable class/interface成员变量必须是Sendable支持的数据类型;
-
Sendable class/interface的成员变量不支持使用!断言;
-
Sendable class/interface的成员变量不支持使用计算属性名;
-
泛型类中的Sendable class,collections.Array,collections.Map,collections.Set的模板类型必须是Sendable类型;
-
Sendable class的内部不允许使用当前模块内上下文环境中定义的变量;
-
Sendable class和Sendable function不能使用除了@Sendable的其它装饰器;
-
不能使用对象字面量/数组字面量初始化Sendable类型;
-
非Sendable类型不可以as成Sendable类型;
-
箭头函数不支持共享;
-
Sendable装饰器修饰类型时仅支持修饰函数类型;
展开说明如下:
👉🏻 Sendable class只能继承自Sendable class
✅ 正确使用案例:
@Sendableclass A {constructor() {}}@Sendableclass B extends A {constructor() {super()}}
❌ 错误使用案例:
class A {constructor() {}}@Sendableclass B extends A {constructor() {super()}}
👉🏻 非Sendable class只能继承自非Sendable class
✅ 正确使用案例:
class A {constructor() {}}class B extends A {constructor() {

最低0.47元/天 解锁文章
1475

被折叠的 条评论
为什么被折叠?



