考虑以下
import 'dart:math';
void main() {
SomeClass someClass = new SomeClass();
Function pointer = ((new Random().nextInt(100) % 2) == 0 ? someClass.fooMethod : someClass.barMethod);
print('$pointer');
}
Closure 'barMethod$0' of Instance of 'MyClass'
假设SomeClass
是不可变的,如何才能将其设为barMethod
或fooMethod
? (也可以接受SomeClass.barMethod
或SomeClass.fooMethod
)
答案 0 :(得分:2)
您可以使用反射来完成此操作,但如果您打算使用dart2js在浏览器中运行它,这可能会很昂贵。这个片段有效:
import 'dart:math' show Random;
import 'dart:mirrors';
void main() {
MyClass myClass = new MyClass();
// Rather than (x % 2 == 0) you could do x.isEven,
// but there's also Random.nextBool()
Function pointer = new Random().nextBool() ? myClass.foo : myClass.bar;
ClosureMirror cm = reflect(pointer) as ClosureMirror;
print(MirrorSystem.getName(cm.function.simpleName));
pointer();
}
class MyClass {
void foo() {}
void bar() {}
}