简体   繁体   English

将整数数组转换为枚举数组

[英]Casting an array of integers to an array of enums

I have an enum that has 4 values: 我有一个有4个值的枚举:

public enum DriveRates 
{ 
    driveSidereal = 0,
    driveLunar = 1, 
    driveSolar = 2, 
    driveKing = 3 
} 

I have an array of values that I want to cast to an array of DriveRates. 我有一个值数组,我想要转换为DriveRates数组。 However when I do var rates = (DriveRates[])ret; 但是,当我做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是一个数字对象数组(可能是整数),它表示Unable to cast object of type 'System.Object[]' to type 'ASCOM.DeviceInterface.DriveRates[]'.

ret = {0,1,2,3} . 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[] . 再次,我试图将枚举值数组转换为枚举数组...好吧,值:)但我正在尝试从类型object[]转换为类型DriveRates[]

You can't just cast the array, if it's really an object[] . 如果它真的是一个object[] ,你不能只是转换数组。 You can create a new array pretty easily though: 可以非常轻松地创建新数组:

var enumArray = originalArray.Cast<DriveRates>().ToArray();

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: 如果它实际上是一个int[]数组,那么你可以进行转换 - 尽管你必须先与C#编译器进行良好的讨论:

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);
        }
    }
}

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. C#编译器不相信从int[]Foo[]的转换(并且在C#的规则中没有)...但是CLR对于这种转换是好的,所以只要你能说服C#编译器一起玩(通过先铸造到object )就可以了。

This doesn't work when the original array is really an object[] though. 当原始数组实际上是一个object[]时,这不起作用

This isn't possible. 这是不可能的。 There is no way to cast between an array of reference types and an array of value types. 无法在引用类型数组和值类型数组之间进行转换。 You will need to manually copy the elements into the new array 您需要手动将元素复制到新数组中

DriveRates[] Convert(object[] source) { 
  var dest = new DriveRates[source.Length];
  for (int i = 0; i < source.Length; i++) { 
    dest[i] = (DriveRates)source[i];
  }
  return dest;
}

...或者使用linq,特别是如果你需要对一行中的每个元素做一些额外的事情:

DriveRates[] enumArray = originalArray.Select(o => (DriveRates)o).ToArray();

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

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