简体   繁体   English

在Dart中打开类类型

[英]Switching on class type in Dart

I'm looking to write a function in a Dart superclass that takes different actions depending on which subclass is actually using it. 我正在寻找在Dart超类中编写一个函数,该函数根据实际使用它的子类采取不同的操作。 Something like this: 像这样的东西:

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 {}

where the idea is that I have some object and want to get a new object of the same (sub)class. 其中的想法是我有一些对象,并希望获得同一(子)类的新对象。

The main question is what type should fooType be? 主要问题是fooType应该是什么类型的? My first thought was Symbol, which leads to easy case statements like case #Bar: , but I don't know how I would populate fooType with a Symbol. 我的第一个想法是Symbol,它导致简单的case语句,如case #Bar: ,但我不知道如何使用Symbol填充fooType The only options I can think of are to do something like Symbol fooType = new Symbol(foo.runtimeType.toString()); 我能想到的唯一选择是做一些像Symbol fooType = new Symbol(foo.runtimeType.toString()); but my understanding is that runtimeType.toString() won't work when converted to javascript. 但我的理解是,当转换为javascript时, runtimeType.toString()将不起作用。 You could get around that by using Mirrors, but this is meant to be a lightweight library, so those aren't on the table. 你可以通过使用Mirrors来解决这个问题,但这应该是一个轻量级的库,所以这些不在桌面上。 Object.runtimeType returns something of the Type class, but I have no idea how to create instances of Type I could use for the case statements. Object.runtimeType返回Type类的一些内容,但我不知道如何创建Type I可用于case语句的实例。 Maybe I'm missing some other piece of the Dart library that is better suited for this? 也许我错过了一些更适合这个的Dart库?

You can use the runtimeType in switch : 您可以在switch使用runtimeType

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

In the case statements the class name is use directly (aka. class literal ). case语句中,类名是直接使用的(aka .class literal )。 This gives a Type object corresponding to the class mentionned. 这给出了一个与提到的类对应的Type对象。 Thus foo.runtimeType can be compared with the specified type. 因此,可以将foo.runtimeType与指定的类型进行比较。

Note that you can not use generics for now in class literals . 请注意, 您现在不能类文字中 使用泛型 Thus case List<int>: is not allowed. 因此,不允许使用case List<int>: :。

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

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