How can I cast int to enum?

后端 未结 30 1556
礼貌的吻别
礼貌的吻别 2020-11-22 00:56

How can an int be cast to an enum in C#?

30条回答
  •  时光取名叫无心
    2020-11-22 01:10

    In my case, I needed to return the enum from a WCF service. I also needed a friendly name, not just the enum.ToString().

    Here's my WCF Class.

    [DataContract]
    public class EnumMember
    {
        [DataMember]
        public string Description { get; set; }
    
        [DataMember]
        public int Value { get; set; }
    
        public static List ConvertToList()
        {
            Type type = typeof(T);
    
            if (!type.IsEnum)
            {
                throw new ArgumentException("T must be of type enumeration.");
            }
    
            var members = new List();
    
            foreach (string item in System.Enum.GetNames(type))
            {
                var enumType = System.Enum.Parse(type, item);
    
                members.Add(
                    new EnumMember() { Description = enumType.GetDescriptionValue(), Value = ((IConvertible)enumType).ToInt32(null) });
            }
    
            return members;
        }
    }
    

    Here's the Extension method that gets the Description from the Enum.

        public static string GetDescriptionValue(this T source)
        {
            FieldInfo fileInfo = source.GetType().GetField(source.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fileInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);            
    
            if (attributes != null && attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return source.ToString();
            }
        }
    

    Implementation:

    return EnumMember.ConvertToList();
    

提交回复
热议问题