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


当前回答

以以下示例为例:

int one = 1;
MyEnum e = (MyEnum)one;

其他回答

从int:

YourEnum foo = (YourEnum)yourInt;

从字符串:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for 
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
    throw new InvalidOperationException(
        $"{yourString} is not an underlying value of the YourEnum enumeration."
    );
}

从一个数字:

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);

我需要两个指示:

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
}

对于字符串,可以执行以下操作:

var result = Enum.TryParse(typeof(MyEnum), yourString, out yourEnum) 

并确保检查结果以确定转换是否失败。

对于int,可以执行以下操作:

MyEnum someValue = (MyEnum)myIntValue;

您可以使用扩展方法。

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

稍微偏离了最初的问题,但我找到了堆栈溢出问题的答案:从枚举中获取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常量来说,这似乎是一个非常整洁的解决方案。