英文:
Dart List all sealed subtypes
问题
我正在寻找一种列出Dart中所有sealed
子类型的方法,类似于Enum.values
,但用于sealed
子类型。
例如,一个enum
可以这样使用:
enum Foo { bar, baz }
main() {
for (final value in Foo.values) {
switch (value) {
case Foo.bar:
print('bar');
case Foo.baz:
print('baz');
}
}
}
// 输出:
// bar
// baz
但是,如果我有一个具有多个子类型的sealed
类:
sealed class Foo {}
class Bar extends Foo {}
class Baz extends Foo {}
在上述情况下,我看不到迭代Bar
和Baz
的方法。我想要的可能是类似于以下方式:
main() {
switch (Foo.subtypes) {
case Bar():
print('bar');
case Baz():
print('baz');
}
}
Foo.subtypes
是无效的,但我希望有一种方法(除了使用镜像或为每个子类型分配enum
之外)。
英文:
I'm looking for a way to list all sealed
subtypes in Dart, like the equivalent of Enum.values
but for sealed
subtypes.
For example, an enum
behaves this way:
enum Foo { bar, baz }
main() {
for (final value in Foo.values) {
switch (value) {
case Foo.bar:
print('bar');
case Foo.baz:
print('baz');
}
}
}
// Prints:
// bar
// baz
But if I have a sealed
class with multiple subtypes:
sealed class Foo {}
class Bar extends Foo {}
class Baz extends Foo {}
In the above case, I don't see a way to iterate over Bar
and Baz
. I suppose I would be looking for something like:
main() {
switch (Foo.subtypes) {
case Bar():
print('bar');
case Baz():
print('baz');
}
}
Foo.subtypes
is not valid, but I was hoping there was a way (other than using mirrors or giving each subtype an enum
).
答案1
得分: 1
没有这样的功能,它确实是反射,并且只应通过 dart:mirrors
来执行。
其中一个原因是没有单一的类型可以表示密封类的泛型子类型的每个实例化。而且,一开始就没有一种简单的方式来迭代类型(Type
对象不是类型)。
英文:
There is no such feature, it really is reflection and should only be done through dart:mirrors
.
One of the reasons is that there is no single type which represents every instantiation of a generic subtype of a sealed class. And there is no easy way to iterate over types to begin with (Type
objects are not types).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论