convert an enum to another type of enum

前端 未结 15 1600
感动是毒
感动是毒 2020-11-30 02:36

I have an enum of for example \'Gender\' (Male =0 , Female =1) and I have another enum from a service which has its own Gender enum (Male =0

15条回答
  •  悲哀的现实
    2020-11-30 03:10

    Based on Justin's answer above I came up with this:

        /// 
        /// Converts Enum Value to different Enum Value (by Value Name) See https://stackoverflow.com/a/31993512/6500501.
        /// 
        /// The type of the enum to convert to.
        /// The source enum to convert from.
        /// 
        /// 
        public static TEnum ConvertTo(this Enum source)
        {
            try
            {
                return (TEnum) Enum.Parse(typeof(TEnum), source.ToString(), ignoreCase: true);
            }
            catch (ArgumentException aex)
            {
                throw new InvalidOperationException
                (
                    $"Could not convert {source.GetType().ToString()} [{source.ToString()}] to {typeof(TEnum).ToString()}", aex
                );
            }
        }
    

提交回复
热议问题