c#中用一行代码将Enum转换为Int数组
本文关键字:Enum 转换 数组 Int 代码 一行 | 更新日期: 2023-09-27 18:07:16
在尝试将枚举转换为其值的int[]时,我最初提出了冗长的:
Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope))
.Cast<Isolations.Enumerations.TypeSelectionScope>().Select(t => (int)t).ToArray()
它工作,但是…嗯,它不漂亮。
我做了一些搜索,发现人们在多行中使用ConvertAll()
来达到这个目的。所以我尝试内联。
Array.ConvertAll(Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope)), value => (int)value)
这将产生一个类型错误,并且在其中添加一些强制转换将使它像第一次尝试一样混乱。
我还尝试了直接转换到int[]
,但无济于事:
Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope)).Cast<int[]>()
添加ToArray()
到此也失败。
那么,什么是单行解决方案,而不是混乱的?
Enumerable.Cast<T>
遍历集合并将每个项强制转换为T
您试图将每个实例强制转换为int[]
-您想将它们强制转换为int
:
.Cast<int>()