Casting an array of integers to an array of enums

孤街醉人 提交于 2019-12-07 00:07:59

问题


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


来源:https://stackoverflow.com/questions/15168855/casting-an-array-of-integers-to-an-array-of-enums

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!