How can I cast int to enum?

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

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

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

    This parses integers or strings to a target enum with partial matching in .NET 4.0 using generics like in Tawani's utility class. I am using it to convert command-line switch variables which may be incomplete. Since an enum cannot be null, you should logically provide a default value. It can be called like this:

    var result = EnumParser<MyEnum>.Parse(valueToParse, MyEnum.FirstValue);
    

    Here's the code:

    using System;
    
    public class EnumParser<T> where T : struct
    {
        public static T Parse(int toParse, T defaultVal)
        {
            return Parse(toParse + "", defaultVal);
        }
        public static T Parse(string toParse, T defaultVal)
        {
            T enumVal = defaultVal;
            if (defaultVal is Enum && !String.IsNullOrEmpty(toParse))
            {
                int index;
                if (int.TryParse(toParse, out index))
                {
                    Enum.TryParse(index + "", out enumVal);
                }
                else
                {
                    if (!Enum.TryParse<T>(toParse + "", true, out enumVal))
                    {
                        MatchPartialName(toParse, ref enumVal);
                    }
                }
            }
            return enumVal;
        }
    
        public static void MatchPartialName(string toParse, ref T enumVal)
        {
            foreach (string member in enumVal.GetType().GetEnumNames())
            {
                if (member.ToLower().Contains(toParse.ToLower()))
                {
                    if (Enum.TryParse<T>(member + "", out enumVal))
                    {
                        break;
                    }
                }
            }
        }
    }
    

    FYI: The question was about integers, which nobody mentioned will also explicitly convert in Enum.TryParse()

    0 讨论(0)
  • 2020-11-22 01:22

    I need two instructions:

    YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enum
    if (Enum.IsDefined(typeof(YourEnum), possibleEnum))
    {
        // Value exists in YourEnum
    }
    
    0 讨论(0)
  • 2020-11-22 01:23

    Alternatively, use an extension method instead of a one-liner:

    public static T ToEnum<T>(this string enumString)
    {
        return (T) Enum.Parse(typeof (T), enumString);
    }
    

    Usage:

    Color colorEnum = "Red".ToEnum<Color>();
    

    OR

    string color = "Red";
    var colorEnum = color.ToEnum<Color>();
    
    0 讨论(0)
  • 2020-11-22 01:24

    If you're ready for the 4.0 .NET Framework, there's a new Enum.TryParse() function that's very useful and plays well with the [Flags] attribute. See Enum.TryParse Method (String, TEnum%)

    0 讨论(0)
  • 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);
    
    
     }
    }
    
    0 讨论(0)
  • 2020-11-22 01:25

    You can use an extension method.

    public static class Extensions
    {
    
        public static T ToEnum<T>(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<T>(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<DaysOfWeeks>();
     var Wed = Wednesday.ToEnum<DaysOfWeeks>();
    
    0 讨论(0)
提交回复
热议问题