C# 将“enum”数组转换为“int”数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/472384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert an array of 'enum' to an array of 'int'
提问by Waleed Eissa
I'm trying to convert an Enum array to an int array:
我正在尝试将 Enum 数组转换为 int 数组:
public enum TestEnum
{
Item1,
Item2
}
int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(Convert.ToInt32));
For some reason Convert.ToInt32 doesn't work when used in Array.ConvertAll, so I had to make some changes:
出于某种原因 Convert.ToInt32 在 Array.ConvertAll 中使用时不起作用,所以我不得不做一些改变:
int[] result = Array.ConvertAll<TestEnum, int>(enumArray, new Converter<TestEnum, int>(ConvertTestEnumToInt));
public static int ConvertTestEnumToInt(TestEnum te)
{
return (int)te;
}
Just out of curiosity, is there any way to have this working without using an extra method?
只是出于好奇,有没有办法在不使用额外方法的情况下进行这项工作?
Regards
问候
采纳答案by Marc Gravell
Just cast using an anonymous method:
只需使用匿名方法进行转换:
int[] result = Array.ConvertAll<TestEnum, int>(
enumArray, delegate(TestEnum value) {return (int) value;});
or with C# 3.0, a lambda:
或使用 C# 3.0,一个 lambda:
int[] result = Array.ConvertAll(enumArray, value => (int) value);
回答by Jay Bazuzi
Luckily for us, C# 3.0 includes a Cast
operation:
幸运的是,C# 3.0 包含一个Cast
操作:
int[] result = enumArray.Cast<int>().ToArray();
If you stop using arrays and start using IEnumerable<>
, you can even get rid of the ToArray()
call.
如果您停止使用数组并开始使用IEnumerable<>
,您甚至可以摆脱ToArray()
调用。
回答by quetzalcoatl
FYI: tested on .Net4ClientProfile and VS2010
仅供参考:在 .Net4ClientProfile 和 VS2010 上测试
Actually, you don't even need to use LINQ. You can just cast it in a normal way, provided that you drop the type down to object
.
实际上,您甚至不需要使用 LINQ。您可以以正常方式转换它,前提是您将类型降低到object
.
Having:
拥有:
enum One { one0, one1, one2, one3 };
enum Two { two0, two1, two2, two3 };
One[] vals = new One[] { One.one0, One.one3 };
we can play:
我们可以玩:
//Two[] aa = (Two[])vals; // impossible
Two[] aa = (Two[])(object)vals; // possible!
Two bb = aa[1]; // == Two.two3
At first, I was really suprised that the second line doesn't throw InvalidCast. But it does not.
起初,我真的很惊讶第二行没有抛出 InvalidCast。但事实并非如此。
Looking at the types explains things a little:
查看类型可以解释一些事情:
bool check2 = bb.GetType().FullName == "Two"; // well, you'd guess that
bool check3 = aa.GetType().FullName == "One[]"; // what?!
Seriously! The aa
array is not Two[]
. The array type has been "lost by variable" when it was cast to object
, but both vals
and (object)vals
of course still refer to the same object. Then, after the following cast, it's still the aa
object, the original array of One[]
, just hidden behind a new variable type.
严重地!所述aa
阵列不是Two[]
。阵列型已被“由变量丢失”,当它被转换为object
,但两者vals
和(object)vals
当然仍指代相同的对象。然后,在下面的转换之后,它仍然是aa
对象, 的原始数组One[]
,只是隐藏在一个新的变量类型后面。
The bb
object/variable has type of Two
because the array's item read as an item of a Two[]
array (along with the variable's types). The real array One[] is concealed by the Two[]
type, so indexing the Two[]
must result in value of Two
type.
的bb
对象/变量的类型Two
,因为阵列的物件读取作为一个项目Two[]
阵列(连同变量的类型)。真正的数组 One[] 被Two[]
类型隐藏,因此索引 theTwo[]
必须导致Two
类型的值。
Furthermore, since the actual type is hidden and since Enum types seem to be treated lightly, let's check another thing:
此外,由于实际类型是隐藏的,并且由于 Enum 类型似乎被轻视,让我们检查另一件事:
var numbers = (int[])(object)vals;
var cc = numbers[0] + 10; // == 10, from one0's value
var dd = numbers[1] + 10; // == 13, from one3's value
and similarly:
同样:
bool check4 = numbers.GetType().FullName == "One[]"; // not System.Int32[]
So, as you might already guess, the other way around is possible too:
因此,正如您可能已经猜到的,反过来也是可能的:
var numbers2 = new int[]{ 0, 2, 99 };
var enums = (One[])(object)numbers2;
One ee = enums[0]; // == One.one0
One ff = enums[1]; // == One.one2
One gg = enums[2]; // == ((One)99)
and int[] also remembers its real type, even if casted to One[]
:
并且 int[] 也记住它的真实类型,即使被强制转换为One[]
:
bool check5 = numbers2.GetType().FullName == "System.Int32[]";
Even further, you cannot trust the as
and is
operators when the array is passed as object
:
更进一步,当数组作为以下参数传递时,您不能信任as
andis
运算符object
:
bool really_true1 = vals is One[];
bool really_true2 = vals is Two[];
bool really_true3 = vals is System.LoaderOptimization[];
This one was a 'gotha!' for me recently.
这是一个“哥达!” 最近对我来说。
It actually reusesthe original array object (instead of duplicating it like with LINQ) and it exposes it as different type - be it Two[] or int[]. It's seems to be a "true cast", no boxing. Much different than LINQ-driven copying&conversion.
它实际上重用了原始数组对象(而不是像使用 LINQ 那样复制它)并将其公开为不同的类型 - 无论是 Two[] 还是 int[]。这似乎是一个“真正的演员”,没有拳击。与 LINQ 驱动的复制和转换大不相同。
回答by Huy Hoang Pham
TestEnumArray.Select(x => (int) x)).ToArray()
TestEnumArray.Select(x => (int) x)).ToArray()
回答by Erik
int[] b = Array.ConvertAll((int[])Enum.GetValues(typeof(TestEnum)), Convert.ToInt32);
int[] b = Array.ConvertAll((int[])Enum.GetValues(typeof(TestEnum)), Convert.ToInt32);
回答by iKnowNothing
This worked like a charm:
这就像一个魅力:
var intArray = enumArray.Select(e => (int)e).ToArray();
as did this:
就像这样做:
var intList = enumArray.Select(e => (int)e).ToList();