问题描述
在Dart中提供枚举之前,我编写了一些麻烦且难以维护的代码来模拟枚举,现在想简化它。我需要以字符串形式获取枚举的值,例如可以用Java完成但不能。
Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it. I need to get the value of the enum as a string such as can be done with Java but cannot.
例如,很少的测试代码片段在其中返回 day.MONDAY每种情况下我想要的是'MONDAY'
For instance little test code snippet returns 'day.MONDAY' in each case when what I want is 'MONDAY"
enum day {MONDAY, TUESDAY}
print( 'Today is $day.MONDAY');
print( 'Today is $day.MONDAY.toString()');
我是否纠正为仅获取'MONDAY',我需要解析字符串?
Am I correct that to get just 'MONDAY' I will need to parse the string?
推荐答案
遗憾的是,您正确地认为toString方法返回 day.MONDAY
,而不是更有用的 MONDAY
。
您可以通过以下方式获取字符串的其余部分:
Sadly, you are correct that the toString method returns "day.MONDAY"
, and not the more useful "MONDAY"
.You can get the rest of the string as:
day theDay = day.MONDAY;
print(theDay.toString().substring(theDay.toString().indexOf('.') + 1));
诚然,这很方便。
如果要迭代所有值,可以使用 day.values
:
If you want to iterate all the values, you can do it using day.values
:
for (day theDay in day.values) {
print(theDay);
}
这篇关于Dart如何获得“价值”一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!