Check that integer type belongs to enum member

前端 未结 7 1301
情歌与酒
情歌与酒 2020-12-30 22:44

I want to check that some integer type belongs to (an) enumeration member.

For Example,

public enum Enum1
{
    member1 = 4,

    member2 = 5,

    m         


        
7条回答
  •  無奈伤痛
    2020-12-30 23:05

    Here's a succinct little snippet from an extension method I wrote a few years ago. Combines TryParse with IsDefined to do it all in one swoop and handle values that don't exist in the enum.

    if (value != null)
    {
        TEnum result;
        if (Enum.TryParse(value.ToString(), true, out result))
        {
            // since an out-of-range int can be cast to TEnum, double-check that result is valid
            if (Enum.IsDefined(typeof(TEnum), result.ToString() ?? string.Empty))
            {
                return result;
            }
        }
    }
    

    Here's the extension for integer values

    public static TEnum ParseToEnum(this int value, TEnum? defaultValue = null, bool useEnumDefault = false) where TEnum : struct
    {
        return ParseToEnumInternal(value, defaultValue, useEnumDefault);
    }
    

    And a usage

    public enum Test
    {
        Value1 = 1,
        Value2 = 3
    }
        
    var intValue = 1;
    var enumParsed = intValue.ParseToEnum(); // converts to Test.Value1
    intValue = 2;
    enumParsed = intValue.ParseToEnum(); // either throws or converts to supplied default
    enumParsed = 3.ParseToEnum(); // converts to Test.Value2
    

    Some people don't like how it dangles off the end of the (potentially nullable) value, but I have an extension that handles null values of nullable types (int?) and I like it myself, so ...

    I can post like a Gist of the whole extension method with all the overloads if you're interested.

提交回复
热议问题