The Dart language does not have enums (yet??). What is the proper or idiomatic way to construct an enum, at least until a language feature arrives?
34023 次
4 に答える
79
Dart now has support for enums.
The rest of this answer is for Dart <= 1.8. If using > 1.8, use Dart's formal support for enums (explained in another answer).
It's true, the Dart language does not (yet?) have enums. There is an open issue for it.
In the meantime, here is an idiomatic Dart snippet to create your own enum.
class Enum {
final _value;
const Enum._internal(this._value);
toString() => 'Enum.$_value';
static const FOO = const Enum._internal('FOO');
static const BAR = const Enum._internal('BAR');
static const BAZ = const Enum._internal('BAZ');
}
Using const constructors means you can use this enum in a switch. Here's an example:
class Fruits {
final _value;
const Fruits._internal(this._value);
toString() => 'Enum.$_value';
static const APPLE = const Fruits._internal('APPLE');
static const PEAR = const Fruits._internal('PEAR');
static const BANANA = const Fruits._internal('BANANA');
}
void main() {
var yummy = Fruits.BANANA;
switch (yummy) {
case Fruits.APPLE:
print('an apple a day');
break;
case Fruits.PEAR:
print('genus Pyrus in the family Rosaceae');
break;
case Fruits.BANANA:
print('open from the bottom, it is easier');
break;
}
}
于 2013-04-06T18:33:06.150 に答える
5
列挙型のトップレベルの定数が好きです。インポートを使用して衝突を修正できます。これにより、列挙型の使用がはるかに冗長になります。
すなわち
if (m == high) {}
それ以外の:
if (m == Meter.high) {}
列挙定義:
class Meter<int> extends Enum<int> {
const Meter(int val) : super (val);
}
const Meter high = const Meter(100);
const Meter middle = const Meter(50);
const Meter low = const Meter(10);
于 2013-04-06T20:54:48.890 に答える