繁体   English   中英

在Dart中打开类类型

[英]Switching on class type in Dart

我正在寻找在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语句,如case #Bar: ,但我不知道如何使用Symbol填充fooType 我能想到的唯一选择是做一些像Symbol fooType = new Symbol(foo.runtimeType.toString()); 但我的理解是,当转换为javascript时, runtimeType.toString()将不起作用。 你可以通过使用Mirrors来解决这个问题,但这应该是一个轻量级的库,所以这些不在桌面上。 Object.runtimeType返回Type类的一些内容,但我不知道如何创建Type I可用于case语句的实例。 也许我错过了一些更适合这个的Dart库?

您可以在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与指定的类型进行比较。

请注意, 您现在不能类文字中 使用泛型 因此,不允许使用case List<int>: :。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM