如何在飞镖中设置通用枚举的类型

发布于 2025-02-11 12:26:35 字数 699 浏览 1 评论 0原文

给定以下枚举:

enum Animal<T> {
  cow,
  goat;
}

如何设置类型?

如果我这样做:

void main() {
  final animal = Animal.cow;
}

飞镖侵入动物的类型为Animal&lt; dynamic&gt;。但是,我无法通过以下任何方法设置类型:

// The static member 'cow' can't be accessed on a class instantiation.
final animal = Animal<int>.cow;

// `animal` is inferred to be `dynamic`, not `Animal<int>`.
final animal = Animal.cow<int>;

当然,我在任何地方都不会使用该类型,但这是我可以想到的最简单的例子来证明我的问题。如何将类型设置为int

Given the enum below:

enum Animal<T> {
  cow,
  goat;
}

How do I set the type?

If I do this:

void main() {
  final animal = Animal.cow;
}

Dart infers the type of animal to be Animal<dynamic>. However, I'm not able to set the type with any of the following ways:

// The static member 'cow' can't be accessed on a class instantiation.
final animal = Animal<int>.cow;

// `animal` is inferred to be `dynamic`, not `Animal<int>`.
final animal = Animal.cow<int>;

Of course, I'm not using the type anywhere, but this is the simplest example I can think of to demonstrate my question. How would I set the type to int?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜清冷一曲。 2025-02-18 12:26:35

枚举值必须是恒定的,因此需要将通用值指定为初始化枚举定义内的枚举值的一部分。

这样的事情:

enum Animal<T> {
  cow<String>(),
  goat<int>();
}

void main() {
  print(Animal.cow.runtimeType); // Animal<String>
  print(Animal.goat.runtimeType); // Animal<int>
}

Enum values must be constant so the generic needs to be specified as part of initializing the enum values inside the enum definition.

So something like this:

enum Animal<T> {
  cow<String>(),
  goat<int>();
}

void main() {
  print(Animal.cow.runtimeType); // Animal<String>
  print(Animal.goat.runtimeType); // Animal<int>
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文