Casting an array of integers to an array of enums

2019-04-26 21:08发布

问题:

I have an enum that has 4 values:

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. 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}. 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[].

回答1:

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

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

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.



回答2:

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


回答3:

...or with linq, especially if you need to do some extra things with every element in one line:

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


标签: c# .net-4.0