How can I cast int to enum?

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

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

30条回答
  •  我寻月下人不归
    2020-11-22 01:18

    The easy and clear way for casting an int to enum in C#:

    public class Program
    {
        public enum Color : int
        {
            Blue   = 0,
            Black  = 1,
            Green  = 2,
            Gray   = 3,
            Yellow = 4
        }
    
        public static void Main(string[] args)
        {
            // From string
            Console.WriteLine((Color) Enum.Parse(typeof(Color), "Green"));
    
            // From int
            Console.WriteLine((Color)2);
    
            // From number you can also
            Console.WriteLine((Color)Enum.ToObject(typeof(Color), 2));
        }
    }
    

提交回复
热议问题