Reflection Dart中的动态实例化

Reflection Dart中的动态实例化,reflection,dart,factory,dart-mirrors,Reflection,Dart,Factory,Dart Mirrors,我需要一个对象,使其他对象的实例。我希望能够传入正在创建的对象类,但它们都需要具有相同的类型,如果它们都可以从相同的值开始,那就太好了: class Cloner{ BaseType prototype; BaseType getAnother(){ BaseType newthing = prototype.clone(); //but there's no clone() in Dart newthing.callsomeBaseTypeMethod();

我需要一个对象,使其他对象的实例。我希望能够传入正在创建的对象类,但它们都需要具有相同的类型,如果它们都可以从相同的值开始,那就太好了:

class Cloner{

  BaseType prototype;

  BaseType getAnother(){
    BaseType newthing = prototype.clone(); //but there's no clone() in Dart
    newthing.callsomeBaseTypeMethod();
    return newthing;
  }
}
所以,prototype可以设置为任何类型为BaseClass的对象,即使它的类是BaseClass的子类。我确信有一种方法可以通过镜像库实现这一点,但我只是想确保我没有错过一些明显的内置工厂方法


我可以看到如何使用泛型:
Cloner
,但是我们无法确保T在编译时是BaseType的子类型,对吗?

为了开始,您可以创建一个小的“构造函数”函数来返回新实例。试试这个:

typedef BaseType Builder();
类克隆器{
建筑商;
克隆人(建筑商);
BaseType getother(){
BaseType newthing=builder();
newthing.callsomeBaseTypeMethod();
返回新事物;
}
}
main(){
var cloner=new cloner(()=>new BaseType());
var thing=cloner.getother();
}

在上面的代码中,我们创建一个typedef来定义一个返回BaseType的函数。

Oh cool!我知道那些typedef迟早会派上用场的。谢谢可能还有其他方法可以做到这一点。希望这对你有用。