可能会在下面的场景中需要循环枚举值

1、为方便前端展示,将返回的数据集合中的枚举名称显示出来。这样前端不需要做任何处理,直接展示即可。

2、向前端输出枚举集合,用于数据筛选,并且前端不需要维护这些集合。后端有修改也不需要通知前端。

方式一:

var dict = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(OperationType));
foreach (var item in values)
{
    dict.Add(item.GetHashCode(), item.ToString());
}
return Task.FromResult(dict);

方式二:

var dict = new Dictionary<int, string>();
var fields = typeof(OperationType).GetFields();
for (int i = 1; i < fields.Length; i++)//下标从1开始
{
    var name = fields[i].Name;
    var value = Enum.Parse(typeof(OperationType), name);
    dict.Add(value.GetHashCode(), name);
}
return Task.FromResult(dict);

最后,顺便提下在开发过程中经时常会用中文作为枚举名称,这样就免去使用 Attribute 还需要再取一次的操作,通过 .ToString() 就能获取枚举名称。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-09
  • 2021-10-07
  • 2022-12-23
  • 2021-07-08
猜你喜欢
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2021-06-12
  • 2022-12-23
  • 2021-09-20
相关资源
相似解决方案