我需要一个创建其他对象实例的对象。我希望能够传入正在创建的对象的类,但它们都需要具有相同的类型,如果它们都可以从相同的值开始,那就太好了:
class Cloner{
BaseType prototype;
BaseType getAnother(){
BaseType newthing = prototype.clone(); //but there's no clone() in Dart
newthing.callsomeBaseTypeMethod();
return newthing;
}
}
因此,原型(prototype)可以设置为 BaseClass 类型的任何对象,即使它的类是 BaseClass 的子类。我确信有一种方法可以使用 mirrors 库来做到这一点,但我只是想确保我不会错过一些明显的内置工厂方式来做到这一点。
我可以看到如何使用泛型进行设置:
Cloner<T>
,但是我们无法在编译时确保 T 是 BaseType 的子类型,对吧?
最佳答案
为了让您开始,您可以创建一个返回新实例的小型“构造函数”。试试这个:
typedef BaseType Builder();
class Cloner {
Builder builder;
Cloner(Builder builder);
BaseType getAnother() {
BaseType newthing = builder();
newthing.callsomeBaseTypeMethod();
return newthing;
}
}
main() {
var cloner = new Cloner(() => new BaseType());
var thing = cloner.getAnother();
}
在上面的代码中,我们创建了一个 typedef 来定义一个返回 BaseType 的函数。
关于reflection - Dart 中的动态实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18992440/