How can I cast int to enum?

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

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

相关标签:
30条回答
  • 2020-11-22 01:17

    Just cast it:

    MyEnum e = (MyEnum)3;
    

    You can check if it's in range using Enum.IsDefined:

    if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
    
    0 讨论(0)
  • 2020-11-22 01:17

    enter image description here

    To convert a string to ENUM or int to ENUM constant we need to use Enum.Parse function. Here is a youtube video https://www.youtube.com/watch?v=4nhx4VwdRDk which actually demonstrate's with string and the same applies for int.

    The code goes as shown below where "red" is the string and "MyColors" is the color ENUM which has the color constants.

    MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), "Red");
    
    0 讨论(0)
  • 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));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:20

    Sometimes you have an object to the MyEnum type. Like

    var MyEnumType = typeof(MyEnum);
    

    Then:

    Enum.ToObject(typeof(MyEnum), 3)
    
    0 讨论(0)
  • 2020-11-22 01:21

    From a string: (Enum.Parse is out of Date, use Enum.TryParse)

    enum Importance
    {}
    
    Importance importance;
    
    if (Enum.TryParse(value, out importance))
    {
    }
    
    0 讨论(0)
  • 2020-11-22 01:22

    This is an flags enumeration aware safe convert method:

    public static bool TryConvertToEnum<T>(this int instance, out T result)
      where T: Enum
    {
      var enumType = typeof (T);
      var success = Enum.IsDefined(enumType, instance);
      if (success)
      {
        result = (T)Enum.ToObject(enumType, instance);
      }
      else
      {
        result = default(T);
      }
      return success;
    }
    
    0 讨论(0)
提交回复
热议问题