How can I cast int to enum?

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

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

30条回答
  •  青春惊慌失措
    2020-11-22 01:25

    Different ways to cast to and from Enum

    enum orientation : byte
    {
     north = 1,
     south = 2,
     east = 3,
     west = 4
    }
    
    class Program
    {
      static void Main(string[] args)
      {
        orientation myDirection = orientation.north;
        Console.WriteLine(“myDirection = {0}”, myDirection); //output myDirection =north
        Console.WriteLine((byte)myDirection); //output 1
    
        string strDir = Convert.ToString(myDirection);
            Console.WriteLine(strDir); //output north
    
        string myString = “north”; //to convert string to Enum
        myDirection = (orientation)Enum.Parse(typeof(orientation),myString);
    
    
     }
    }
    

提交回复
热议问题