Dart中如何为整数索引命名以通过属性名访问列表元素?
更优实现方法推荐
你的当前写法依赖枚举索引与列表元素的顺序绑定,一旦枚举顺序调整或列表元素错位,就会引发错误,而且无法保证类型安全。这里给你几种更可靠的实现方式:
1. 用类封装属性(最推荐)
直接定义一个类来封装所有属性,不仅可读性极强,还能确保每个属性的类型正确,完全摆脱对索引的依赖:
class Scooter { final int power; final int capacity; final String model; Scooter(this.power, this.capacity, this.model); } void main() { final scooter = Scooter(50, 1000, "Suzuki"); print(scooter.model); // 直接通过属性名访问 }
2. 使用Map关联枚举与属性值
如果想保留枚举的用法,用Map将枚举成员和对应属性值绑定,比依赖索引更安全,就算枚举顺序变动也不会影响取值:
enum ScooterProperty { power, capacity, model } void main() { final scooterProps = { ScooterProperty.power: 50, ScooterProperty.capacity: 1000, ScooterProperty.model: "Suzuki", }; print(scooterProps[ScooterProperty.model]); }
3. 增强枚举(适合属性类型统一的场景)
如果所有属性都是同一类型,可以用Dart的增强枚举直接给成员赋值,但像你这样属性类型混杂(int、String)的情况,这种方法就不适用了,这里给个同类型场景的示例参考:
enum ScooterIntProperty { power(50), capacity(1000); final int value; const ScooterIntProperty(this.value); } void main() { print(ScooterIntProperty.power.value); }
内容的提问来源于stack exchange,提问作者Andrey
相关产品推荐
相关产品推荐

