How can I cast int to enum?

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

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

30条回答
  •  渐次进展
    2020-11-22 01:13

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace SamplePrograme
    {
        public class Program
        {
            public enum Suit : int
            {
                Spades = 0,
                Hearts = 1,
                Clubs = 2,
                Diamonds = 3
            }
    
            public static void Main(string[] args)
            {
                //from string
                Console.WriteLine((Suit) Enum.Parse(typeof(Suit), "Clubs"));
    
                //from int
                Console.WriteLine((Suit)1);
    
                //From number you can also
                Console.WriteLine((Suit)Enum.ToObject(typeof(Suit) ,1));
            }
        }
    }
    

提交回复
热议问题