当前位置: 首页> 教育> 幼教 > 郑州人才网_黄骅市属于哪里_学it什么培训机构好_整站优化推广

郑州人才网_黄骅市属于哪里_学it什么培训机构好_整站优化推广

时间:2025/7/12 3:07:04来源:https://blog.csdn.net/kid_devil/article/details/146308369 浏览次数:0次
郑州人才网_黄骅市属于哪里_学it什么培训机构好_整站优化推广

目录

  • HarmonyOS Next 状态管理:Local 装饰器实践
  • HarmonyOS Next 状态管理:Param 装饰器实践
  • HarmonyOS Next 状态管理:Once 装饰器实践
  • HarmonyOS Next 状态管理:Event 装饰器实践
  • HarmonyOS Next 状态管理:!! 状态装饰器实践
  • HarmonyOS Next 状态管理:@ObserverV2和@Trace 装饰器实践
  • HarmonyOS Next 状态管理:Provider和Consumer 装饰器实践
  • HarmonyOS Next 状态管理:Monitor 装饰器实践
  • HarmonyOS Next 状态管理:Computed 装饰器实践
  • # HarmonyOS Next 状态管理:Type 装饰器实践

一. @Type 修饰器概述

@Type 主要用于标记类属性的类型,以确保在序列化和反序列化过程中不会丢失属性的类型信息。它通常与 @ObservedV2 和 PersistenceV2 结合使用,用于实现复杂对象的持久化。

二. @Type的基本用法

2.1 基本语法
@Type(type: Class | BuiltInType)
  • type:指定属性的类型,可以是自定义类或内置类型(如 ArrayDateMapSet 等)。
2.2 使用示例
@ObservedV2
class SampleChild {@Trace p1: number = 0;p2: number = 10;
}@ObservedV2
class Sample {@Type(SampleChild) // 标记属性 f 的类型为 SampleChild@Trace f: SampleChild = new SampleChild();
}
  • 在上面的代码中,@Type(SampleChild) 标记了属性 f 的类型为 SampleChild,确保在序列化和反序列化过程中不会丢失 SampleChild 的类型信息。

三. @Type的限制

3.1 只能用于 @ObservedV2 装饰的类

@Type 只能用于被 @ObservedV2 装饰的类中,不能用于普通类或自定义组件中。

@ObservedV2
class Info {@Type(Sample)@Trace sample: Sample = new Sample(); // 正确用法
}@Observed
class Info2 {@Type(Sample)sample: Sample = new Sample(); // 错误用法,不能用在 @Observed 装饰的类中
}@ComponentV2
struct Index {@Type(Sample)sample: Sample = new Sample(); // 错误用法,不能用在自定义组件中build() {}
}
3.2 不支持某些类型
  • 不支持 collections.Setcollections.Map 等集合类型。
  • 不支持非内置类型,如 PixelMapNativePointerArrayList 等原生类型。
  • 不支持简单类型,如 stringnumberboolean 等。

四. 实践探索

@Type 通常与 PersistenceV2 结合使用,用于实现复杂对象的持久化。

import { Type, PersistenceV2 } from '@kit.ArkUI';@ObservedV2
class SampleChild {@Trace p1: number = 0;p2: number = 10;
}@ObservedV2
export class Sample {@Type(SampleChild) // 标记属性 f 的类型为 SampleChild@Trace f: SampleChild = new SampleChild();
}@Entry
@ComponentV2
struct Page {prop: Sample = PersistenceV2.connect(Sample, () => new Sample())!;build() {Column({ space: 20 }) {Text(`Page1 add 1 to prop.p1: ${this.prop.f.p1}`).onClick(() => {this.prop.f.p1++;  })}.width('100%')}
}

五.参考

  • 鸿蒙官方文档
关键字:郑州人才网_黄骅市属于哪里_学it什么培训机构好_整站优化推广

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: