可以使用枚举的values属性获取所有枚举对象,然后遍历判断字符串是否与枚举对象的名称相同,如果相同就返回该枚举对象。例如:

enum Fruit {
  apple,
  banana,
  orange
}

Fruit getFruit(String name) {
  for (Fruit fruit in Fruit.values) {
    if (fruit.toString() == 'Fruit.' + name) {
      return fruit;
    }
  }
  return null;
}

void main() {
  Fruit fruit = getFruit('apple');
  print(fruit); // Fruit.apple
}

在上面的代码中,getFruit函数接受一个字符串参数name,然后遍历Fruit枚举的所有枚举对象,判断名称是否匹配,如果匹配就返回该枚举对象,否则返回null。在main函数中,我们调用getFruit函数,传入字符串'apple',然后得到对应的Fruit枚举对象并输出。

标签: 教育


原文地址: https://gggwd.com/t/topic/cQR 著作权归作者所有。请勿转载和采集!