1# \@Type装饰器:标记类属性的类型 2 3为了实现序列化类时不丢失属性的复杂类型,开发者可以使用\@Type装饰器装饰类属性。 4 5 6\@Type的目的是标记类属性,配合PersistenceV2使用,防止序列化时类丢失。在阅读本文档前,建议提前阅读:[PersistenceV2](./arkts-new-persistencev2.md)。 7 8>**说明:** 9> 10>\@Type从API version 12开始支持。 11> 12 13 14## 概述 15 16\@Type标记类属性,使得类属性序列化时不丢失类型信息,便于类的反序列化。 17 18 19## 装饰器说明 20 21| \@Type装饰器 | 说明 | 22| ------------------- | ------------------------------------------------------------ | 23| 装饰器参数 | type:类型。 | 24| 可装饰的类型 | Object class以及Array、Date、Map、Set等内嵌类型。 | 25 26 27## 使用限制 28 291、只能用在\@ObservedV2装饰的类中,不能用在自定义组件中。 30 31```ts 32class Sample { 33 data: number = 0; 34} 35@ObservedV2 36class Info { 37 @Type(Sample) 38 @Trace sample: Sample = new Sample(); // 正确用法 39} 40@Observed 41class Info2 { 42 @Type(Sample) 43 sample: Sample = new Sample(); // 错误用法,不能用在@Observed装饰的类中,编译时报错 44} 45@ComponentV2 46struct Index { 47 @Type(Sample) 48 sample: Sample = new Sample(); // 错误用法,不能用在自定义组件中 49 build() { 50 } 51} 52``` 53 542、不支持collections.Set、collections.Map等类型。 55 563、不支持非buildin类型,如PixelMap、NativePointer、ArrayList等Native类型。 57 584、不支持简单类型,如string、number、boolean等。 59 605、@Type不支持构造函数含参的类。 61 62## 使用场景 63 64### 持久化数据 65 66数据页面 67```ts 68import { Type } from '@kit.ArkUI'; 69 70// 数据中心 71@ObservedV2 72class SampleChild { 73 @Trace p1: number = 0; 74 p2: number = 10; 75} 76 77@ObservedV2 78export class Sample { 79 // 对于复杂对象需要@Type修饰,确保序列化成功 80 @Type(SampleChild) 81 @Trace f: SampleChild = new SampleChild(); 82} 83``` 84 85页面 86```ts 87import { PersistenceV2 } from '@kit.ArkUI'; 88import { Sample } from '../Sample'; 89 90@Entry 91@ComponentV2 92struct Page { 93 prop: Sample = PersistenceV2.connect(Sample, () => new Sample())!; 94 95 build() { 96 Column() { 97 Text(`Page1 add 1 to prop.p1: ${this.prop.f.p1}`) 98 .fontSize(30) 99 .onClick(() => { 100 this.prop.f.p1++; 101 }) 102 } 103 } 104} 105``` 106