Enum ToString with user friendly strings

后端 未结 23 1787
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:44

My enum consists of the following values:

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

I want to be able to

23条回答
  •  粉色の甜心
    2020-11-22 12:25

    This is an update to Ray Booysen's code that uses the generic GetCustomAttributes method and LINQ to make things a bit tidier.

        /// 
        /// Gets the value of the  on an struct, including enums.  
        /// 
        /// The type of the struct.
        /// A value of type 
        /// If the struct has a Description attribute, this method returns the description.  Otherwise it just calls ToString() on the struct.
        /// Based on http://stackoverflow.com/questions/479410/enum-tostring/479417#479417, but useful for any struct.
        public static string GetDescription(this T enumerationValue) where T : struct
        {
            return enumerationValue.GetType().GetMember(enumerationValue.ToString())
                    .SelectMany(mi => mi.GetCustomAttributes(false),
                        (mi, ca) => ca.Description)
                    .FirstOrDefault() ?? enumerationValue.ToString();
        }   
    

提交回复
热议问题