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


当前回答

您只需执行以下操作:

int intToCast = 1;
TargetEnum f = (TargetEnum) intToCast ;

为了确保只计算正确的值​​否则可以抛出异常:

int intToCast = 1;
if (Enum.IsDefined(typeof(TargetEnum), intToCast ))
{
    TargetEnum target = (TargetEnum)intToCast ;
}
else
{
   // Throw your exception.
}

请注意,使用IsDefined的成本很高,甚至不仅仅是强制转换,因此决定是否使用它取决于您的实现。

其他回答

我正在使用这段代码将int转换为枚举:

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

我觉得这是最好的解决方案。

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

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

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

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

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

MyEnum someValue = (MyEnum)myIntValue;

您只需使用显式转换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
    }
}

您可以使用扩展方法。

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