Enum to dictionary

前端 未结 5 1371
南方客
南方客 2020-12-15 16:37

I want to implement an extension method which converts an enum to a dictionary:

public static Dictionary ToDictionary(this Enum @enum)
{
           


        
5条回答
  •  暖寄归人
    2020-12-15 17:11

    You can't use type1 as a generic parameter, because it is a variable, not a type.

    The following code does something similar to what your code shows:

    public static Dictionary ToDictionary()
        where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum)
            throw new ArgumentException("Type must be an enumeration");
        return Enum.GetValues(typeof(TEnum)).Cast().
                ToDictionary(e => Enum.GetName(typeof(TEnum), e));
    }
    

    Use it like this:

    ToDictionary()
    

    But I am not really sure, this is, what you expected?

    Additionally, it has one problem: You can pass any struct, not just enums and this will result in a runtime exception. See Jon's answer for more details about that.

提交回复
热议问题