有没有办法将字符串转换为枚举?
enum eCommand{fred, joe, harry}
eCommand theCommand= cast(eCommand, 'joe');??
Run Code Online (Sandbox Code Playgroud)
我想我只需要搜索枚举(例如循环)。
干杯
史蒂夫
Pra*_*tti 14
Dart 2.6 引入了enum类型方法。最好在Topic或String本身上调用 getter 以通过命名扩展获取相应的转换。我更喜欢这种技术,因为我不需要导入新的包,节省内存并用 OOP 解决问题。
当我在不使用更多情况下更新枚举时,我也会收到编译器警告default,因为我没有详尽地处理开关。
这是一个例子:
enum Topic { none, computing, general }
extension TopicString on String {
Topic get topic {
switch (this) {
case 'computing':
return Topic.computing;
case 'general':
return Topic.general;
case 'none':
return Topic.none;
}
}
}
extension TopicExtension on Topic {
String get string {
switch (this) {
case Topic.computing:
return 'computing';
case Topic.general:
return 'general';
case Topic.none:
return 'none';
}
}
}
Run Code Online (Sandbox Code Playgroud)
这真的很容易使用和理解,因为我没有创建任何额外的类来进行转换:
var topic = Topic.none;
final string = topic.string;
topic = string.topic;
Run Code Online (Sandbox Code Playgroud)
(-:
我对枚举的状态感到恼火,并建立了一个库来处理这个问题:
https://pub.dev/packages/enum_to_string
基本用法:
import 'package:enum_to_string:enum_to_string.dart';
enum TestEnum { testValue1 };
main(){
final result = EnumToString.fromString(TestEnum.values, "testValue1");
// TestEnum.testValue1
}
Run Code Online (Sandbox Code Playgroud)
仍然比我想要的更冗长,但可以完成工作。
小智 9
我想出了一个灵感来自https://pub.dev/packages/enum_to_string的解决方案,它可以用作 List 上的简单扩展
extension EnumTransform on List {
String string<T>(T value) {
if (value == null || (isEmpty)) return null;
var occurence = singleWhere(
(enumItem) => enumItem.toString() == value.toString(),
orElse: () => null);
if (occurence == null) return null;
return occurence.toString().split('.').last;
}
T enumFromString<T>(String value) {
return firstWhere((type) => type.toString().split('.').last == value,
orElse: () => null);
}
}
Run Code Online (Sandbox Code Playgroud)
用法
enum enum Color {
red,
green,
blue,
}
var colorEnum = Color.values.enumFromString('red');
var colorString: Color.values.string(Color.red)
Run Code Online (Sandbox Code Playgroud)
从 Dart 2.15 开始,您可以使用name属性和byName()方法:
enum eCommand { fred, joe, harry }
eCommand comm = eCommand.fred;
assert(comm.name == "fred");
assert(eCommand.values.byName("fred") == comm);
Run Code Online (Sandbox Code Playgroud)
请注意,如果字符串未被识别为枚举中的有效成员,该byName方法将抛出异常。ArgumentError
对于 Dart 枚举来说,这有点麻烦。
有关解决方案,请参阅字符串中的枚举。
如果您需要的不仅仅是枚举的最基本功能,通常最好使用旧式枚举 - 具有 const 成员的类。
请参阅如何使用 Dart 构建枚举?对于旧式枚举
| 归档时间: |
|
| 查看次数: |
14234 次 |
| 最近记录: |