简体   繁体   English

在C#中将Enum单行转换为Int数组

[英]One-line converting Enum to Int array in C#

In trying to convert an enumeration into an int[] of its values, I initially came up with the long-winded: 在尝试将枚举转换为其值的int []时,我最初想到了冗长的步骤:

Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope))
.Cast<Isolations.Enumerations.TypeSelectionScope>().Select(t => (int)t).ToArray()

It works, but.. well, it ain't pretty. 它有效,但是..它不是很漂亮。

I did some searching, and found people using ConvertAll() for this purpose, over multiple lines. 我做了一些搜索,发现人们为此在多行上使用ConvertAll() So I tried it inline. 所以我尝试内联。

Array.ConvertAll(Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope)), value => (int)value)

This generates a type error, and adding some casting within is going to make it as messy as the first attempt. 这会产生类型错误,并且在其中添加一些强制转换将使其像第一次尝试一样混乱。

I also tried a direct cast to an int[] to no avail: 我也尝试了直接转换为int[]无济于事:

Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope)).Cast<int[]>()

Adding a ToArray() onto this fails also. ToArray()添加到此方法也会失败。

So, what's a single-line solution to this that isn't messy? 那么,什么是单行解决方案呢?

Enumerable.Cast<T> iterates through a collection and casts each item to T Enumerable.Cast<T>遍历一个集合并将每个项目强制转换为T

You're trying to cast each instance to int[] - you want to cast them to int instead: 您正在尝试将每个实例强制转换为int[] -您想将其强制转换为int

.Cast<int>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM