Dart是否支持枚举? [英] Does Dart support enumerations?
本文介绍了Dart是否支持枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Dart支持枚举吗?例如:
Does Dart support enumerations? For instance:
enum myFruitEnum { Apple, Banana }
对文档进行粗略搜索表明没有。
A cursory search of the docs suggests no.
推荐答案
href =http://news.dartlang.org/2014/11/dart-18-library-improvements-and.html =noreferrer> 1.8 ,您可以使用如下的枚举:
Beginning 1.8, you can use enums like this:
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]);
}
:
The old approach before 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
语句:
Those static constants within the class are compile time constants, and this class can now be used in, for example, switch
statements:
var a = Fruit.APPLE;
switch (a) {
case Fruit.APPLE:
print('Yes!');
break;
}
这篇关于Dart是否支持枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文