Dart是否支持枚举?例如:
enum myFruitEnum { Apple, Banana }
粗略搜索文档表明没有。
答案 0 :(得分:104)
从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;
}
答案 1 :(得分:6)
使用r41815 Dart获得原生Enum支持,请参阅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]
value:Status.none,index:0
value:Status.running,index:1
value:Status.stopped,index:2
value:Status.paused,index:3
跑步:Status.running,1
运行索引:Status.running
一个限制是,它不可能为枚举项设置自定义值,它们会自动编号。
此草案中的更多详情https://www.dartlang.org/docs/spec/EnumsTC52draft.pdf
答案 2 :(得分:3)
... 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) { ... }
在我看来更清楚使用。对应用程序结构进行编程有点困难,但在某些情况下,它更好更清晰。
答案 3 :(得分:3)
将来可能会有枚举。但在Enum has landed之前,您可以执行以下操作:
class Fruit {
static final APPLE = new Fruit._();
static final BANANA = new Fruit._();
static get values => [APPLE, BANANA];
Fruit._();
}
答案 4 :(得分:3)
这种方法怎么样:
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;
}
}
}
答案 5 :(得分:1)
是的!在Dart中进行枚举实际上非常有用:
enum fruits{
BANANA, APPLE, ORANGE
}
答案 6 :(得分:0)