是否可以从此类内部或外部向现有类动态添加实例方法或 setter?
最佳答案
不,您不能向类(class)添加真正的成员。
我说真正的成员是因为你可以用noSuchMethod()模拟这样的特征.这里有一个例子:
@proxy
class A {
final dynamicMethods = <Symbol, Function>{};
noSuchMethod(Invocation i) {
if (i.isMethod && dynamicMethods.containsKey(i.memberName)) {
return Function.apply(dynamicMethods[i.memberName],
i.positionalArguments, i.namedArguments);
}
return super.noSuchMethod(i);
}
}
main() {
final a = new A();
a.dynamicMethods[#sayHello] = () => print('hello');
a.sayHello();
}
在未来这也许是可能的。请参阅 the article on Mirrors 中的这段摘录:
We’d like to support more powerful reflective features in the future. These would include mirror builders, designed to allow programs to extend and modify themselves, and a mirror-based debugging API as well.
关于dart - 如何在 Dart 的类中动态创建方法或 setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20237128/