Enum ToString with user friendly strings

后端 未结 23 2168
伪装坚强ぢ
伪装坚强ぢ 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:39

    I created a reverse extension method to convert the description back into an enum value:

    public static T ToEnumValue(this string enumerationDescription) where T : struct
    {
        var type = typeof(T);
    
        if (!type.IsEnum)
            throw new ArgumentException("ToEnumValue(): Must be of enum type", "T");
    
        foreach (object val in System.Enum.GetValues(type))
            if (val.GetDescription() == enumerationDescription)
                return (T)val;
    
        throw new ArgumentException("ToEnumValue(): Invalid description for enum " + type.Name, "enumerationDescription");
    }
    

提交回复
热议问题