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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 08:19:39  来源:igfitidea点击:

How to cast int to enum?

提问by lomaxx

How can an intbe cast to an enumin C#?

如何在 C# 中将anint强制转换为 an enum

采纳答案by FlySwat

From a string:

从字符串:

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

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

From an int:

从一个整数:

YourEnum foo = (YourEnum)yourInt;

Update:

更新:

From number you can also

从号码你也可以

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

回答by abigblackman

Take the following example:

以下面的例子为例:

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

回答by Matt Hamilton

Just cast it:

只需投射它:

MyEnum e = (MyEnum)3;

You can check if it's in range using Enum.IsDefined:

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

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

回答by L. D.

Sometimes you have an object to the MyEnumtype. Like

有时你有一个MyEnum类型的对象。喜欢

var MyEnumType = typeof(MyEnumType);

Then:

然后:

Enum.ToObject(typeof(MyEnum), 3)

回答by Tawani

Below is a nice utility class for Enums

下面是一个很好的枚举实用程序类

public static class EnumHelper
{
    public static int[] ToIntArray<T>(T[] value)
    {
        int[] result = new int[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = Convert.ToInt32(value[i]);
        return result;
    }

    public static T[] FromIntArray<T>(int[] value) 
    {
        T[] result = new T[value.Length];
        for (int i = 0; i < value.Length; i++)
            result[i] = (T)Enum.ToObject(typeof(T),value[i]);
        return result;
    }


    internal static T Parse<T>(string value, T defaultValue)
    {
        if (Enum.IsDefined(typeof(T), value))
            return (T) Enum.Parse(typeof (T), value);

        int num;
        if(int.TryParse(value,out num))
        {
            if (Enum.IsDefined(typeof(T), num))
                return (T)Enum.ToObject(typeof(T), num);
        }

        return defaultValue;
    }
}

回答by Evan M

If you have an integer that acts as a bitmask and could represent one or more values in a [Flags] enumeration, you can use this code to parse the individual flag values into a list:

如果您有一个整数作为位掩码并且可以表示 [Flags] 枚举中的一个或多个值,则可以使用以下代码将各个标志值解析为一个列表:

for (var flagIterator = 0; flagIterator < 32; flagIterator++)
{
    // Determine the bit value (1,2,4,...,Int32.MinValue)
    int bitValue = 1 << flagIterator;

    // Check to see if the current flag exists in the bit mask
    if ((intValue & bitValue) != 0)
    {
        // If the current flag exists in the enumeration, then we can add that value to the list
        // if the enumeration has that flag defined
        if (Enum.IsDefined(typeof(MyEnum), bitValue))
            Console.WriteLine((MyEnum)bitValue);
    }
}

Note that this assumes that the underlying type of the enumis a signed 32-bit integer. If it were a different numerical type, you'd have to change the hardcoded 32 to reflect the bits in that type (or programatically derive it using Enum.GetUnderlyingType())

请注意,这假定 的基础类型enum是有符号的 32 位整数。如果它是不同的数字类型,则必须更改硬编码 32 以反映该类型中的位(或使用 以编程方式派生Enum.GetUnderlyingType()

回答by MSkuta

I am using this piece of code to cast int to my enum:

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

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

I find it the best solution.

我认为这是最好的解决方案。

回答by Ryan Russon

If you're ready for the 4.0 .NETFramework, there's a new Enum.TryParse()function that's very useful and plays well with the [Flags] attribute. See Enum.TryParse Method (String, TEnum%)

如果您已准备好使用 4.0 .NETFramework,那么有一个新的Enum.TryParse()函数,它非常有用并且与 [Flags] 属性配合得很好。参见Enum.TryParse 方法(字符串,TEnum%)

回答by Abdul Munim

Alternatively, use an extension method instead of a one-liner:

或者,使用扩展方法而不是单行:

public static T ToEnum<T>(this string enumString)
{
    return (T) Enum.Parse(typeof (T), enumString);
}

Usage:

用法:

Color colorEnum = "Red".ToEnum<Color>();

OR

或者

string color = "Red";
var colorEnum = color.ToEnum<Color>();

回答by Sébastien Duval

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

对于数值,这更安全,因为无论如何它都会返回一个对象:

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