How can I cast int to enum?

后端 未结 30 1474
礼貌的吻别
礼貌的吻别 2020-11-22 00:56

How can an int be cast to an enum in C#?

30条回答
  •  清酒与你
    2020-11-22 00:59

    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:

    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 enum is 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())

提交回复
热议问题