首页 > 解决方案 > 给定字符串作为方法名称时动态调用类方法

问题描述

考虑以下 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

解决方案


是的,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, []);
  }
}

推荐阅读