Dart 是否支持枚举?例如:
enum myFruitEnum { Apple, Banana }
对文档的粗略搜索表明没有。
从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 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]
值:Status.none,索引:0
值:Status.running,索引:1
值:Status.stopped,索引:2
值:Status.paused,索引:3
运行:Status.running,1
运行索引:Status.running
一个限制是不可能为枚举项设置自定义值,它们会自动编号。
本草案中的更多详细信息https://www.dartlang.org/docs/spec/EnumsTC52draft.pdf
枚举应该在将来可用。但是在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;
}
}
}
是的!在 Dart 中进行枚举实际上非常有用:
enum fruits{
BANANA, APPLE, ORANGE
}