Cast int to enum in C#

2018-12-31 04:21发布

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

标签: c# enums casting
22条回答
高级女魔头
2楼-- · 2018-12-31 04:59

Sometimes you have an object to the MyEnum type. Like

var MyEnumType = typeof(MyEnumType);

Then:

Enum.ToObject(typeof(MyEnum), 3)
查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 05:01

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));
        }
    }
查看更多
倾城一夜雪
4楼-- · 2018-12-31 05:02

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");
查看更多
栀子花@的思念
5楼-- · 2018-12-31 05:02

Following is slightly better extension method

public static string ToEnumString<TEnum>(this int enumValue)
        {
            var enumString = enumValue.ToString();
            if (Enum.IsDefined(typeof(TEnum), enumValue))
            {
                enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
            }
            return enumString;
        }
查看更多
有味是清欢
6楼-- · 2018-12-31 05:04

I am using this piece of code to cast int to my enum:

if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;
else { //handle it here, if its not defined }

I find it the best solution.

查看更多
牵手、夕阳
7楼-- · 2018-12-31 05:04

For numeric values, this is safer as it will return an object no matter what:

public static class EnumEx
{
    static public bool TryConvert<T>(int value, out T result)
    {
        result = default(T);
        bool success = Enum.IsDefined(typeof(T), value);
        if (success)
        {
            result = (T)Enum.ToObject(typeof(T), value);
        }
        return success;
    }
}
查看更多
登录 后发表回答