Enum to list as an extension?

后端 未结 6 1359
花落未央
花落未央 2021-02-19 19:00

I have various enums that I use as sources for dropdown lists, In order to provide for a user-friendly description, I added a Description attribute to each enum, an

6条回答
  •  遇见更好的自我
    2021-02-19 19:37

    What is the correct way to use it as an extension (using the above 2 methods)?

    There is no correct way to use it as an extension. Extension methods (similar to instance methods) are used when you have a value (instance) and for instance want to get some information related to that value. So the extension method would make sense if you want to get the description of a single enum value.

    However, in your case the information you need (the list of enum value/description pairs) is not tied to a specific enum value, but to the enum type. Which means you just need a plain static generic method similar to Enum.TryParse. Ideally you would constrain the generic argument to allow only enum, but this type of constraint is not supported (yet), so we'll use (similar to the above system method) just where TEnum : struct and will add runtime check.

    So here is a sample implementation:

    public static class EnumInfo
    {
        public static List> GetList()
            where TEnum : struct
        {
            if (!typeof(TEnum).IsEnum) throw new InvalidOperationException();
            return ((TEnum[])Enum.GetValues(typeof(TEnum)))
               .ToDictionary(k => k, v => ((Enum)(object)v).GetAttributeOfType().Description)
               .ToList();
        }
    }
    

    and usage:

    public enum MyEnum
    {
        [Description("Foo")]
        A,
        [Description("Bar")]
        B,
        [Description("Baz")]
        C,
    }
    
    var list = EnumInfo.GetList();
    

提交回复
热议问题