How can I cast int to enum?

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

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

30条回答
  •  梦毁少年i
    2020-11-22 01:05

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

    public static class EnumEx
    {
        static public bool TryConvert(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;
        }
    }
    

提交回复
热议问题