简体   繁体   中英

C#: Generic list of enum values

Is there a way to create a method that gets an enum type as a parameter, and returns a generic list of the enum underlying type from it's values, no matter if the underlying type is int\\short byte etc'...
I saw this answer of Jon Skeet, but it looks way too complicated.

If you want to pass in a Type , it can't really be usefully generic - you'd have to return a single type that isn't directly related to the input , hence something like:

    public static Array GetUnderlyingEnumValues(Type type)
    {
        Array values = Enum.GetValues(type);
        Type underlyingType = Enum.GetUnderlyingType(type);
        Array arr = Array.CreateInstance(underlyingType, values.Length);
        for (int i = 0; i < values.Length; i++)
        {
            arr.SetValue(values.GetValue(i), i);
        }
        return arr;
    }

This is a strongly-typed vector underneath, so you could cast that to int[] etc.

While Marc's answer isn't wrong its somewhat unnecessary. Enum.GetValues(type) returns a TEnum[] so this method is kind of unnecessary as if you know the underlying type you can just cast TEnum[] to its underlying type array.

var underlyingArray = (int[])Enum.GetValues(typeof(StringComparison));

is valid C# that will compile and won't throw an exception at runtime. Since you wanted a list once you have the array you can pass it to the List<Tunderlying> constructor or you can just call the ToArray() extension method.

Edit: you could write the function as such::

public static TUnderlying[] GetValuesAs<TUnderlying>(type enumType)
{
     return Enum.GetValues(enumType) as TUnderlying[];
}

But then you would have to know the underlying type first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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