mercredi 26 avril 2017

Get Enumvalues via reflection from nested enum in generic class

I need to print out enum values from certain types i accquire through relfection. This works fine mostly. However if the enum is declared within a generic type Enum.GetValues throws the following exception:

[System.NotSupportedException: Cannot create arrays of open type. ]
at System.Array.InternalCreate(Void* elementType, Int32 rank, Int32* pLengths, Int32* pLowerBounds)
at System.Array.CreateInstance(Type elementType, Int32 length) at System.Array.UnsafeCreateInstance(Type elementType, Int32 length)
at System.RuntimeType.GetEnumValues()

Full code for reproduction :

using System;

public class Program
{
    public static void Main()
    {
       var enumType= typeof(Foo<>.Bar);

       Console.WriteLine(enumType.IsEnum);

       foreach(var value in Enum.GetValues(enumType))
       {
           Console.WriteLine(value);
       }
    }

}

public class Foo<T>
{
    public enum Bar
    {
        A = 1,
        B = 2
    }
}

Or test it here

Is this desired behaviour and how do I work arround?

Construction a type would be a workarround but inacceptable for me, since it would ge too complicated.





Aucun commentaire:

Enregistrer un commentaire