铸造整数数组来枚举数组 [英] Casting an array of integers to an array of enums
问题描述
我有一个枚举,有4个值:
I have an enum that has 4 values:
public enum DriveRates
{
driveSidereal = 0,
driveLunar = 1,
driveSolar = 2,
driveKing = 3
}
我有,我想转换为DriveRates数组值的数组。然而,当我这样做 VAR率=(DriveRates [])RET;
,与 RET
是数字的对象数组(可能是整数),它说无法转换类型的对象System.Object的[]'输入'ASCOM.DeviceInterface.DriveRates []'。
I have an array of values that I want to cast to an array of DriveRates. However when I do var rates = (DriveRates[])ret;
, with ret
being an object array of numbers (probably integers), it says Unable to cast object of type 'System.Object[]' to type 'ASCOM.DeviceInterface.DriveRates[]'.
RET
= {0,1,2,3}
。我应该怎么做这个代替。同样,我试图枚举值的数组转换为枚举的数组......嗯,价值观:)不过我想从类型转换 [对象]
键入 DriveRates []
。
ret
={0,1,2,3}
. How should I do this instead. Again, I am trying to convert an array of enum values to an array of enum...well, values :) But I'm trying to convert from type object[]
to type DriveRates[]
.
推荐答案
您不能只是投阵列,如果它是一个真正的 [对象]
。您的可以的创建一个新的阵列pretty的很容易,但:
You can't just cast the array, if it's really an object[]
. You can create a new array pretty easily though:
var enumArray = originalArray.Cast<DriveRates>().ToArray();
如果它是的实际上的的 INT []
阵列,开始时,你可以投 - 尽管你必须很好地交谈C#编译器首先:
If it were actually an int[]
array to start with, you could cast - although you'd have to talk nicely to the C# compiler first:
using System;
class Program
{
enum Foo
{
Bar = 1,
Baz = 2
}
static void Main()
{
int[] ints = new int[] { 1, 2 };
Foo[] foos = (Foo[]) (object) ints;
foreach (var foo in foos)
{
Console.WriteLine(foo);
}
}
}
C#编译器并不认为有从一个转换 INT [
]到富[]
(和没有,C#的规则)之内......但CLR是罚款与此转换,所以只要你能说服C#编译器一起玩(通过转换成对象
第一)还行吧。
The C# compiler doesn't believe that there's a conversion from int[]
to Foo[]
(and there isn't, within the rules of C#)... but the CLR is fine with this conversion, so as long as you can persuade the C# compiler to play along (by casting to object
first) it's fine.
本的不的工作时,原来的数组是一个真正的 [对象]
虽然。
This doesn't work when the original array is really an object[]
though.
这篇关于铸造整数数组来枚举数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!