C# Getting Enum values

后端 未结 11 1202
深忆病人
深忆病人 2020-12-12 15:25

I have a enum containing the following (for example):

  • UnitedKingdom,
  • UnitedStates,
  • France,
  • Portugal

In my code I use

11条回答
  •  长情又很酷
    2020-12-12 15:51

    I tried to submit an edit to Scott Ivey's answer, but it was rejected, here's yet another answer. My relatively minor edits:

    1) I fixed Alex's error of System.ArgumentException: Field 'value__' defined on type 'MyClass.EnumHelperTest+MyCountryEnum' is not a field on the target object which is of type 'System.Reflection.RtFieldInfo'. Got it from here.

    2) Added a return so you can actually copy/paste it and it'll work.

    3) Changed the SortedDictionary to Dictionary because SortedDictionary always sorts by the key, in this case the string Description. There's no reason to alphabetize the Description. In fact, sorting it destroys the original order of the enum. Dictionary doesn't preserve the enum order either, but at least it doesn't imply order like SortedDictionary does.

    enum MyCountryEnum
    {    
        [Description("UK")]
        UnitedKingdom = 0,    
    
        [Description("US")]
        UnitedStates = 1,    
    
        [Description("FR")]
        France = 2,    
    
        [Description("PO")]
        Portugal = 3
    }
    
    public static string GetDescription(this Enum value)
    {
        var type = value.GetType();
    
        var fi = type.GetField(value.ToString());
    
        var descriptions = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
    
        return descriptions.Length > 0 ? descriptions[0].Description : value.ToString();
    }
    
    public static Dictionary GetBoundEnum() where T : struct, IConvertible
    {
        // validate.
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an Enum type.");
        }
    
        var results = new Dictionary();
    
        FieldInfo[] fieldInfos = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static);
    
        foreach (var fi in fieldInfos)
        {
    
            var value = (T)fi.GetValue(fi);
            var description = GetDescription((Enum)fi.GetValue(fi));
    
            if (!results.ContainsKey(description))
            {
                results.Add(description, value);
            }
        }
        return results;
    }
    

提交回复
热议问题