C# Getting Enum values

后端 未结 11 1197
深忆病人
深忆病人 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:41

    I prefer to use the DescriptionAttribute on my enums. Then, you can use the following code to grab that description from the enum.

    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 SortedDictionary GetBoundEnum() where T : struct, IConvertible
    {
        // validate.
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be an Enum type.");
        }
    
        var results = new SortedDictionary();
    
        FieldInfo[] fieldInfos = typeof(T).GetFields();
    
        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;
    }
    

    And then to get my bound enum list, its simply a call to

    GetBoundEnum()
    

    To get a single enum's description, you'd just use the extension method like this

    string whatever = MyCountryEnum.UnitedKingdom.GetDescription();
    

提交回复
热议问题