ArkTS中,如何将Object类型的对象转换为具体类的对象呢

代码如下:

cpp 复制代码
class Person {
  private age: number;

  constructor(age: number) {
    this.age = age;
  }

  getAge(): number {
    return this.age;
  }
}

let map: Map<string, Object> = new Map();
map.set('person', new Person(18));

let person: Person | undefined = map.get('person') as Person;

if (person instanceof Person) {
  console.log("age: " +person.getAge()); // 输出:18
} else {
  console.error('对象不是Person类型');
}

在这个示例中,我将Map的值类型设置为Object,这样我就可以避免在将对象放入**Map**时进行类型检查。

然后,当我从**Map** 中检索对象时,我使用类型断言as 将其转换为**Person**类型。

最后,我使用**instanceof操作符来检查对象是否真的是Person**类型的实例,以确保我不会调用一个不存在的方法或访问一个不存在的属性。

相关推荐
chenyingjian2 天前
鸿蒙|性能优化-概述与工具使用
harmonyos
二流小码农2 天前
鸿蒙开发:路由组件升级,支持页面一键创建
android·ios·harmonyos
TT_Close2 天前
【Flutter×鸿蒙】debug 包也要签名,这点和 Android 差远了
android·flutter·harmonyos
TT_Close3 天前
【Flutter×鸿蒙】FVM 不认鸿蒙 SDK?4步手动塞进去
flutter·swift·harmonyos
hqk3 天前
鸿蒙项目实战:手把手带你实现 WanAndroid 布局与交互
android·前端·harmonyos
TT_Close3 天前
【Flutter×鸿蒙】一个"插队"技巧,解决90%的 command not found
flutter·harmonyos
Hcourage4 天前
鸿蒙工程获取C/C++代码覆盖
harmonyos
二流小码农4 天前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
万少4 天前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
Huang兄5 天前
鸿蒙-List和Grid拖拽排序:仿微信小程序删除效果
harmonyos·arkts·arkui