How to assign string values to enums and use that value in a switch

后端 未结 10 1766
小鲜肉
小鲜肉 2021-02-02 10:45

Basically a series of titles will be passed into the switch statement and I need to compare them against the string values of the enum. But I have little to no idea how to do th

10条回答
  •  [愿得一人]
    2021-02-02 10:59

    Just sharing my solution. By downloading the nuget package Extension.MV, a method is available for getting the string from a Enum Description

    public enum Prefix
    {
        [Description("doctor")]
        doctor = 1,
        [Description("mr")]
        mr = 2,
        [Description("mrs")]
        mrs = 3
    }
    
    public static class PrefixAdapter {
    
        public static string ToText(this Prefix prefix) {
            return prefix.GetEnumDescription();
        }
    
        public static Prefix ToPrefix(this string text) {
            switch (text)
            {
                case "doctor"
                    return Prefix.doctor;
                case "mr"
                    return Prefix.mr;
                case "ms"
                    return Prefix.mrs;
            }
        }
    }
    

提交回复
热议问题