Dart 如何获取“值"一个枚举 [英] Dart How to get the "value" of an enum
问题描述
在 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.
例如,当我想要的是MONDAY"时,小测试代码片段在每种情况下都返回day.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));
诚然,不太方便.
另一种将枚举名称作为字符串获取的方法,这种方法更短,但效率也较低,因为它也为字符串的第一部分创建了一个不必要的字符串,是:
Another way to get the enum name as a string, one which is shorter, but also less efficient because it creates an unnecessary string for first part of the string too, is:
theDay.toString().split('.').last
如果性能无关紧要,那可能就是我要写的,只是为了简洁.
If performance doesn't matter, that's probably what I'd write, just for brevity.
如果你想迭代所有的值,你可以使用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 如何获取“值"一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!