How can I cast int to enum?

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

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

30条回答
  •  误落风尘
    2020-11-22 01:25

    You can use an extension method.

    public static class Extensions
    {
    
        public static T ToEnum(this string data) where T : struct
        {
            if (!Enum.TryParse(data, true, out T enumVariable))
            {
                if (Enum.IsDefined(typeof(T), enumVariable))
                {
                    return enumVariable;
                }
            }
    
            return default;
        }
    
        public static T ToEnum(this int data) where T : struct
        {
            return (T)Enum.ToObject(typeof(T), data);
        }
    }
    

    Use it like the below code:

    Enum:

    public enum DaysOfWeeks
    {
        Monday = 1,
        Tuesday = 2,
        Wednesday = 3,
        Thursday = 4,
        Friday = 5,
        Saturday = 6,
        Sunday = 7,
    }
    

    Usage:

     string Monday = "Mon";
     int Wednesday = 3;
     var Mon = Monday.ToEnum();
     var Wed = Wednesday.ToEnum();
    

提交回复
热议问题