1# \@Type装饰器:标记类属性的类型 2 3为了实现序列化类时不丢失属性的复杂类型,开发者可以使用\@Type装饰器装饰类属性。 4 5>**说明:** 6> 7>\@Type从API version 12开始支持。 8> 9>当前状态管理(V2试用版)仍在逐步开发中,相关功能尚未成熟,建议开发者尝鲜试用。 10 11 12## 概述 13 14\@Type标记类属性,使得类属性序列化时不丢失类型信息,便于类的反序列化。 15 16 17## 装饰器说明 18 19| \@Type装饰器 | 说明 | 20| ------------------- | ------------------------------------------------------------ | 21| 装饰器参数 | type:类型。 | 22| 可装饰的类型 | Object class以及Array、Date、Map、Set等内嵌类型。 | 23 24 25## 使用限制 26 271、只能用在class内中; 28 292、不支持collections.Set、collections.Map等类型; 30 313、不支持非buildin类型,如PixelMap、NativePointer、ArrayList等Native类型; 32 334、不支持简单类型,如string、number、boolean等。 34 35## 使用场景 36 37### 持久化数据 38 39数据页面 40```ts 41import { Type } from '@kit.ArkUI'; 42 43// 数据中心 44@ObservedV2 45class SampleChild { 46 @Trace p1: number = 0; 47 p2: number = 10; 48} 49 50@ObservedV2 51export class Sample { 52 // 对于复杂对象需要@Type修饰,确保序列化成功 53 @Type(SampleChild) 54 @Trace f: SampleChild = new SampleChild(); 55} 56``` 57 58页面 59```ts 60import { PersistenceV2 } from '@kit.ArkUI'; 61import { Sample } from '../Sample'; 62 63@Entry 64@ComponentV2 65struct Page { 66 prop: Sample = PersistenceV2.connect(Sample, () => new Sample())!; 67 68 build() { 69 Column() { 70 Text(`Page1 add 1 to prop.p1: ${this.prop.f.p1}`) 71 .fontSize(30) 72 .onClick(() => { 73 this.prop.f.p1++; 74 }) 75 } 76 } 77} 78``` 79