代码之家  ›  专栏  ›  技术社区  ›  orj

如何从System.Enum转换为基整数?

  •  86
  • orj  · 技术社区  · 16 年前

    例如,我想要的是这样的东西:

    // Trivial example, not actually what I'm doing.
    class Converter
    {
        int ToInteger(System.Enum anEnum)
        {
            (int)anEnum;
        }
    }
    

    但这似乎不起作用。Resharper报告无法将“System.Enum”类型的表达式强制转换为“int”类型。

    现在我已经想出了这个解决方案,但我宁愿有更有效的。

    class Converter
    {
        int ToInteger(System.Enum anEnum)
        {
            return int.Parse(anEnum.ToString("d"));
        }
    }
    

    有什么建议吗?

    8 回复  |  直到 16 年前
        1
  •  151
  •   Hannele    12 年前

    如果你不想投,

    Convert.ToInt32()
    

    直接演员(via) (int)enumValue )这是不可能的。请注意,这也是“危险的”,因为枚举可以有不同的底层类型( int long byte

    更正式地说: System.Enum 没有直接的继承关系 Int32 (尽管两者都是 ValueType s) ,因此显式强制转换在类型系统中不能正确

        2
  •  47
  •   BFree    16 年前

    我通过对一个对象进行强制转换,然后对一个int进行强制转换,使其工作:

    public static class EnumExtensions
    {
        public static int ToInt(this Enum enumValue)
        {
            return (int)((object)enumValue);
        }
    }
    

    这是丑陋的,可能不是最好的方式。我会继续捣乱,看看我能不能想出更好的办法。。。。

    编辑:我正要发布转换。ToInt32(enumValue)也可以工作,并且注意到MartinStettner比我做得快。

    public static class EnumExtensions
    {
        public static int ToInt(this Enum enumValue)
        {
            return Convert.ToInt32(enumValue);
        }
    }
    

    测试:

    int x = DayOfWeek.Friday.ToInt();
    Console.WriteLine(x); // results in 5 which is int value of Friday
    

    public static class Helpers
    {
        public static int ToInt(Enum enumValue)
        {
            return Convert.ToInt32(enumValue);
        }
    }
    
        static void Main(string[] args)
        {
            Console.WriteLine(Helpers.ToInt(DayOfWeek.Friday));
        }
    
        3
  •  16
  •   Drew Noakes    10 年前

    如果你需要转换 任何 枚举到其基础类型(并非所有枚举都由 int )然后您可以使用:

    return System.Convert.ChangeType(
        enumValue,
        Enum.GetUnderlyingType(enumValue.GetType()));
    
        4
  •  10
  •   LukeH    16 年前

    为什么需要用助手方法重新发明轮子?投一张票是完全合法的 enum 值设置为其基础类型。

    它的打字更少,在我看来更可读,使用。。。

    int x = (int)DayOfWeek.Tuesday;
    

    …而不是像。。。

    int y = Converter.ToInteger(DayOfWeek.Tuesday);
    // or
    int z = DayOfWeek.Tuesday.ToInteger();
    
        5
  •  4
  •   Community Mohan Dere    8 年前

    根据我的回答 here :

    鉴于 e

    Enum e = Question.Role;
    

    然后这些工作:

    int i = Convert.ToInt32(e);
    int i = (int)(object)e;
    int i = (int)Enum.Parse(e.GetType(), e.ToString());
    int i = (int)Enum.ToObject(e.GetType(), e);
    

    public static int GetIntValue(this Enum e)
    {
        return e.GetValue<int>();
    }
    
    public static T GetValue<T>(this Enum e) where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
    {
        return (T)(object)e;
    }
    

    现在您可以拨打:

    e.GetValue<int>(); //or
    e.GetIntValue();
    
        6
  •  1
  •   jpoh    16 年前

    铸造 System.Enum int 对我来说很好(它也在 MSDN ).也许这是一个重拾音的错误。

        7
  •  1
  •   eisenpony    7 年前

    由于枚举被限制为byte、sbyte、short、ushort、int、uint、long和ulong,我们可以做出一些假设。

    通过使用最大的可用容器,我们可以避免转换过程中出现异常。不幸的是,使用哪个容器还不清楚,因为ulong将爆炸为负数,long将爆炸为long.MaxValue和ulong.MaxValue之间的数。我们需要根据基础类型在这些选择之间切换。

    当然,当结果不符合整数时,你仍然需要决定该怎么做。我认为施法是可以的,但仍然存在一些问题:

    1. 对于基于字段空间大于int(long和ulong)的类型的枚举,某些枚举的计算结果可能相同。

    public int ToInt(Enum e)
    {
      unchecked
      {
        if (e.GetTypeCode() == TypeCode.UInt64)
          return (int)Convert.ToUInt64(e);
        else
          return (int)Convert.ToInt64(e);
      }
    }
    
        8
  •  0
  •   Dwedit    5 年前

    如果你读了 Convert.ToInt32 Enum IConvertible ,然后打电话 ToInt32(null) .

        9
  •  -1
  •   Michael Kniskern    16 年前

    不要忘记枚举类型本身有一堆静态辅助函数。如果您只想将枚举实例转换为相应的整数类型,那么强制转换可能是最有效的方法。

    我认为ReSharper在抱怨,因为Enum不是任何特定类型的枚举,而枚举本身派生自标量值类型,而不是Enum。如果您需要以通用方式进行适应性转换,我想说这可以很好地满足您的需要(请注意,枚举类型本身也包含在通用方式中:

    public static EnumHelpers
    {
        public static T Convert<T, E>(E enumValue)
        {
            return (T)enumValue;
        }
    }
    

    然后可以这样使用:

    public enum StopLight: int
    {
        Red = 1,
        Yellow = 2,
        Green = 3
    }
    
    // ...
    
    int myStoplightColor = EnumHelpers.Convert<int, StopLight>(StopLight.Red);
    

    我不知道该怎么说,但上面的代码甚至可能得到C#的类型推断的支持,允许以下内容:

    int myStoplightColor = EnumHelpers.Convert<int>(StopLight.Red);