dart - 给定字符串作为方法名称时动态调用类方法
问题描述
考虑以下 JavaScript 代码:
class Thing {
foo() {console.log('foo')}
bar() {console.log('bar')}
}
const thing = new Thing();
for (let i = 0; i < 5; i++) {
const methodName = i % 2 !== 0
? 'foo'
: 'bar';
thing[methodName](); // this bit here is the important part
}
在 Dart 中这样的事情是可能的吗?我正在寻找动态调用方法。Dart 中认可的处理方式是什么?if / else 链或 switch 是唯一的方法吗?
void main() {
TestThing test = TestThing();
for (int i = 0; i < 5; i++) {
final method = i.isOdd
? 'foo'
: 'bar';
test[method](); // ERROR: The operator '[]' isn't defined for the class TestThing
}
}
class TestThing {
TestThing();
int foo() {
print('foo');
return 1;
}
int bar() {
print('bar');
return 2;
}
}
解决方案
是的,dart:mirrors
图书馆可以做到这一点。这是使用您的示例实现的方式:
import 'dart:mirrors';
class TestThing {
int foo() {
print('foo');
return 1;
}
int bar() {
print('bar');
return 2;
}
}
void main() {
TestThing test = TestThing();
InstanceMirror mirror = reflect(test);
for (int i = 0; i < 5; i++) {
final method = i.isOdd
? 'foo'
: 'bar';
mirror.invoke(method, []);
}
}
推荐阅读
- javascript - cancelScheduledValues(x) 后跟 setValueCurveAtTime(x) 抛出错误
- python - 如何使用 Impala 和 Python 代码同时运行查询?
- python-3.x - Selenium - 使用 URL 登录失败
- r - 我怎样才能使用外部功能?
- flutter - 如何在 App-Bar 中的图像文件下方放置文本?
- docker - 将容器中的文件夹公开为 Kubernetes Pod 中的卷
- django - 表记录异常增加:从订单 ID 54 到 86?
- java - 如何以编程方式查找对方法的所有引用?
- .net - 将 VB6.Format 转换为 [variable].ToString() 问题
- paw-app - Paw Oauth2 隐式授权流程:授权响应中的状态无效