You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已知方法名称为字符串时,如何在Smalltalk对象上调用该方法?

Smalltalk通过字符串方法名调用对象方法的解决方法

问题场景

现有如下代码,需要通过字符串形式的方法名调用Foobar对象的doSomething方法:

Object subclass: Foobar [
  doSomething [
    'Doing something!' displayNl.
  ]
]

(Foobar new) doSomething.
methodName := 'doSomething'.
"What now?"

尝试执行以下代码时触发expected expression错误:

perform: 'doSomething' asSymbol with: (Foobar new)

错误原因

perform:是对象的消息,必须发送给目标对象,而非直接作为独立语句调用。你写的代码把目标对象当成了perform:的参数,这是逻辑错误。

正确实现

基础调用(无参数方法)

  1. 将字符串方法名转换为Symbol(Smalltalk中方法标识符以Symbol类型存储)
  2. 向目标对象发送perform:消息,传入转换后的Symbol

修正后的代码:

Object subclass: Foobar [
  doSomething [
    'Doing something!' displayNl.
  ]
]

| foobarInstance methodName |
foobarInstance := Foobar new.
methodName := 'doSomething'.
foobarInstance perform: methodName asSymbol.

带参数方法的调用

如果目标方法需要参数,使用对应参数数量的perform系列消息:

  • 单参数:perform:with:
  • 双参数:perform:with:with:
  • 更多参数可使用perform:withArguments:传入参数数组

示例(假设Foobar有do: aString方法):

Object subclass: Foobar [
  do: aString [
    ('Doing: ', aString) displayNl.
  ]
]

| foobarInstance methodName |
foobarInstance := Foobar new.
methodName := 'do:'.
foobarInstance perform: methodName asSymbol with: 'test task'.

内容的提问来源于stack exchange,提问作者yabobay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 22:12:43