Dart 列出所有封闭子类型

huangapple go评论90阅读模式
英文:

Dart List all sealed subtypes

问题

我正在寻找一种列出Dart中所有sealed子类型的方法,类似于Enum.values,但用于sealed子类型。

例如,一个enum可以这样使用:

  1. enum Foo { bar, baz }
  2. main() {
  3. for (final value in Foo.values) {
  4. switch (value) {
  5. case Foo.bar:
  6. print('bar');
  7. case Foo.baz:
  8. print('baz');
  9. }
  10. }
  11. }
  12. // 输出:
  13. // bar
  14. // baz

但是,如果我有一个具有多个子类型的sealed类:

  1. sealed class Foo {}
  2. class Bar extends Foo {}
  3. class Baz extends Foo {}

在上述情况下,我看不到迭代BarBaz的方法。我想要的可能是类似于以下方式:

  1. main() {
  2. switch (Foo.subtypes) {
  3. case Bar():
  4. print('bar');
  5. case Baz():
  6. print('baz');
  7. }
  8. }

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:

  1. enum Foo { bar, baz }
  2. main() {
  3. for (final value in Foo.values) {
  4. switch (value) {
  5. case Foo.bar:
  6. print('bar');
  7. case Foo.baz:
  8. print('baz');
  9. }
  10. }
  11. }
  12. // Prints:
  13. // bar
  14. // baz

But if I have a sealed class with multiple subtypes:

  1. sealed class Foo {}
  2. class Bar extends Foo {}
  3. 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:

  1. main() {
  2. switch (Foo.subtypes) {
  3. case Bar():
  4. print('bar');
  5. case Baz():
  6. print('baz');
  7. }
  8. }

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).

huangapple
  • 本文由 发表于 2023年6月22日 04:43:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定