Given an object, which is an array of enum values, how can I get Enum [] without knowing the type of enum

How can I convert from a typed variable of an object containing an array of some type of enumeration to Enum []? In other words:

// Somewhere in the code we have: public enum MyEnum {This,That};
// Somewhere else in the code we have: public enum TheirEnum {What,Ever};
// In other parts of the code we have additional enum types

// Now, given:
object enumArrayOfSomeType=...; // Maybe it of type MyEnum[] or TheirEnum[] or 
                                // SomeOtherEnum[]

// I want to say
Enum[] someEnumArray=enumArrayOfSomeType as Enum[];

Unfortunately, the code presented always results in a null value in someEnumArray.

Is there any way to do this?

Update :

I suppose I expected the covariance of the array to start, but maybe I expected too much (i.e. the covariance of the arrays is wild).

In addition, thanks to Chris Sinclair for pointing out in the comments to the accepted answer that covariance of arrays is used only for references to types that are listed, of course, no. (See NET Array covariance rules on MSDN .)

+4
1

, , MyEnum[] Enum[]. LINQ :

Enum[] someEnumArray = ((IEnumerable)enumArrayOfSomeType).Cast<Enum>().ToArray();

: , , ToArray() IEnumerable<Enum>:

IEnumerable<Enum> someEnumArray = ((IEnumerable)enumArrayOfSomeType).Cast<Enum>();

, .

EDITx2: , , , , . MSDN 12.5 :

A B, ( 6.1.4) ( 6.2.3) A B, A [R] B [R]

+6

Source: https://habr.com/ru/post/1546020/


All Articles