在Dart中开启课程类型 [英] Switching on class type in Dart
问题描述
我希望在Dart超类中编写一个函数,该函数根据实际使用的子类采取不同的操作。像这样的东西:
I'm looking to write a function in a Dart superclass that takes different actions depending on which subclass is actually using it. 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.
主要问题是 fooType
应该是什么类型?我的第一个想法是Symbol,它会导致产生简单的案例陈述,例如 case #Bar:
,但我不知道如何填充 fooType
和一个符号。我唯一想到的选择是做 Symbol fooType = new Symbol(foo.runtimeType.toString());
之类的事情,但是我的理解是 runtimeType.toString()
转换为javascript后将无法使用。您可以通过使用Mirrors来解决此问题,但这是一个轻量级的库,因此不在表中。 Object.runtimeType
返回 Type
类的内容,但是我不知道如何创建<$ c $的实例c> Type 我可以用于case语句。也许我错过了Dart库中其他更适合此功能的部分?
The main question is what type should fooType
be? 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. The only options I can think of are to do something like Symbol fooType = new Symbol(foo.runtimeType.toString());
but my understanding is that runtimeType.toString()
won'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 on the table. 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. Maybe I'm missing some other piece of the Dart library that is better suited for this?
推荐答案
您可以使用 runtimeType
在 switch
中:
class Foo {
Foo getAnother(Foo foo) {
switch (foo.runtimeType) {
case Bar:
return new Bar();
case Baz:
return new Baz();
}
return null;
}
}
在情况下
语句直接使用类名(也称为类文字)。这给出了与该类相对应的 Type 对象提到。因此,可以将 foo.runtimeType
与指定的类型进行比较。
In the case
statements the class name is use directly (aka. class literal). This gives a Type object corresponding to the class mentionned. Thus foo.runtimeType
can be compared with the specified type.
请注意您不能在类文字中暂时使用泛型。因此,不允许 case List< int>:
。
Note that you can not use generics for now in class literals. Thus case List<int>:
is not allowed.
这篇关于在Dart中开启课程类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!