Dart 列出所有封闭子类型

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

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

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

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

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:

确定