HarmonyOS 使用Record有什么好处

HarmonyOS
2024-12-27 14:40:51
863浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

使用Record可以像map一样动态的调用一些对象或者方法,下面以方法举例:Record<string, Function>的方式实现字符串去调用方法。

定义时:

export class dddd {
  fun : Record<string, Function> = {};
  constructor() {
    this.fun={'ssss':this.ddd1,'sdss':this.ccc}
  }
  ddd1(){
    console.log('ddd1')
  }
  ccc(){
    console.log('cccc')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

调用时:

import display from '@ohos.display';
import { dddd } from './FunTest';
@Entry
@Component
struct DisplayTest {
  private ddd : dddd = new dddd()
  build() {
    Column({space:20}){
      Button('Test')
        .type(ButtonType.Capsule)
        .onClick(() => {
          this.ddd.fun['ssss']()
          this.ddd.fun['sdss']()
        })
        .width('50%')
    }
    .width("100%")
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

实际运用中可以通过字符串动态的调用方法。

分享
微博
QQ
微信
回复
2024-12-27 17:03:56


相关问题
能否嵌套定义 Record<string,Record>
2311浏览 • 1回复 待解决
HarmonyOS Record HashMap map类型选择
2483浏览 • 2回复 待解决
HarmonyOS Record和HashMap的区别
714浏览 • 2回复 待解决
harmonyos的MDNS什么用,如何使用
209浏览 • 0回复 待解决
Blank组件什么作用,怎样使用?
1043浏览 • 1回复 待解决
HarmonyOS 什么方法使用两段包名
673浏览 • 1回复 待解决
HarmonyOS 使用prefetch4.0什么注意事项
723浏览 • 1回复 待解决