Dart是否支持枚举?

Dart是否支持枚举? 例如:

enum myFruitEnum { Apple, Banana } 

对文档的粗略searchbuild议否。

从1.8开始,你可以使用像这样的枚举:

 enum Fruit { apple, banana } main() { var a = Fruit.apple; switch (a) { case Fruit.apple: print('it is an apple'); break; } // get all the values of the enums for (List<Fruit> value in Fruit.values) { print(value); } // get the second value print(Fruit.values[1]); } 

1.8之前的老办法:

 class Fruit { static const APPLE = const Fruit._(0); static const BANANA = const Fruit._(1); static get values => [APPLE, BANANA]; final int value; const Fruit._(this.value); } 

这些类中的静态常量是编译时间常量,现在可以在例如switch语句中使用这个类:

 var a = Fruit.APPLE; switch (a) { case Fruit.APPLE: print('Yes!'); break; } 

随着r41815飞镖得到本地枚举支持见http://dartbug.com/21416和可以使用像;

 enum Status { none, running, stopped, paused } void main() { print(Status.values); Status.values.forEach((v) => print('value: $v, index: ${v.index}')); print('running: ${Status.running}, ${Status.running.index}'); print('running index: ${Status.values[1]}'); } 

[Status.none,Status.running,Status.stopped,Status.paused]
值:Status.none,索引:0
值:Status.running,索引:1
值:Status.stopped,索引:2
值:Status.paused,索引:3
正在运行:Status.running,1
运行索引:Status.running

限制是不可能为枚举项目设置自定义值,它们会自动编号。

在这个草案的更多细节docs/spec/EnumsTC52draft.html

枚举应在将来可用。 但是在Enum登陆之前,你可以这样做:

 class Fruit { static final APPLE = new Fruit._(); static final BANANA = new Fruit._(); static get values => [APPLE, BANANA]; Fruit._(); } 

这和这可能是你的问题的答案:

 ... for the technology preview it was decided to leave it out and just use static final fields for now. It may be added later. 

你仍然可以做这样的事情:

 interface ConnectionState { } class Connected implements ConnectionState { } class Connecting implements ConnectionState { } class Disconnected implements ConnectionState { } //later ConnectionState connectionState; if (connectionState is Connecting) { ... } 

这在我看来是更清晰的使用。 对应用程序结构编程有点困难,但在某些情况下,它更好,更清晰。

这个方法怎么样:

 class FruitEnums { static const String Apple = "Apple"; static const String Banana = "Banana"; } class EnumUsageExample { void DoSomething(){ var fruit = FruitEnums.Apple; String message; switch(fruit){ case(FruitEnums.Apple): message = "Now slicing $fruit."; break; default: message = "Now slicing $fruit via default case."; break; } } }