首页 文章

在Dart中打开类类型

提问于
浏览
10

我正在寻找在Dart超类中编写一个函数,该函数根据实际使用它的子类采取不同的操作 . 像这样的东西:

class Foo {
  Foo getAnother(Foo foo) {
    var fooType = //some code here to extract fooType from foo;
    switch (fooType) {
      case //something about bar here:
        return new Bar();
      case //something about baz here:
        return new Baz();
    }
  }
}

class Bar extends Foo {}

class Baz extends Foo {}

其中的想法是我有一些对象,并希望获得同一(子)类的新对象 .

主要问题是 fooType 应该是什么类型的?我的第一个想法是Symbol,它导致像 case #Bar: 这样简单的案例陈述,但我不知道如何用符号填充 fooType . 我能想到的唯一选择是做 Symbol fooType = new Symbol(foo.runtimeType.toString()); 之类的事情,但我的理解是 runtimeType.toString() 赢了't work when converted to javascript. You could get around that by using Mirrors, but this is meant to be a lightweight library, so those aren' t . Object.runtimeType 返回 Type 类的一些内容,但我不知道如何创建 Type 的实例我可以用于case语句 . 也许我错过了一些更适合这个的Dart库?

1 回答

  • 13

    您可以在 switch 中使用 runtimeType

    class Foo {
      Foo getAnother(Foo foo) {
        switch (foo.runtimeType) {
          case Bar:
            return new Bar();
          case Baz:
            return new Baz();
        }
        return null;
      }
    }
    

    case 语句中,类名直接使用(aka .class literal) . 这给出了与提到的类相对应的Type对象 . 因此 foo.runtimeType 可以与指定的类型进行比较 .

    请注意类文字中的you can not use generics for now . 因此不允许 case List<int>: .

相关问题