如何在C#中将int转换为枚举?


当前回答

您只需使用显式转换Cast int to enum或enum to int

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine((int)Number.three); //Output=3

        Console.WriteLine((Number)3);// Outout three
        Console.Read();
    }

    public enum Number
    {
        Zero = 0,
        One = 1,
        Two = 2,
        three = 3
    }
}

其他回答

我需要两个指示:

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
}

只要投它:

MyEnum e = (MyEnum)3;

使用Enum.IsDefined检查它是否在范围内:

if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }

您可以使用扩展方法。

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);
    }
}

使用如下代码:

枚举:

public enum DaysOfWeeks
{
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
    Sunday = 7,
}

用法:

 string Monday = "Mon";
 int Wednesday = 3;
 var Mon = Monday.ToEnum<DaysOfWeeks>();
 var Wed = Wednesday.ToEnum<DaysOfWeeks>();

这是一个标志枚举感知安全转换方法:

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;
}

稍微偏离了最初的问题,但我找到了堆栈溢出问题的答案:从枚举中获取int值很有用。使用public const int财产创建一个静态类,允许您轻松收集一组相关的int常量,然后在使用它们时不必将它们强制转换为int。

public static class Question
{
    public static readonly int Role = 2;
    public static readonly int ProjectFunding = 3;
    public static readonly int TotalEmployee = 4;
    public static readonly int NumberOfServers = 5;
    public static readonly int TopBusinessConcern = 6;
}

显然,一些枚举类型的功能将丢失,但对于存储一堆数据库id常量来说,这似乎是一个非常整洁的解决方案。