Enum.Parse(), surely a neater way?

前端 未结 5 1959
猫巷女王i
猫巷女王i 2020-12-14 05:32

Say I have an enum,

public enum Colours
{
    Red,
    Blue
}

The only way I can see of parsing them is doing something like:



        
5条回答
  •  一整个雨季
    2020-12-14 06:15

    I believe that 4.0 has Enum.TryParse

    Otherwise use an extension method:

    public static bool TryParse(this Enum theEnum, string valueToParse, out T returnValue)
    {
        returnValue = default(T);
        int intEnumValue;
        if (Int32.TryParse(valueToParse, out intEnumValue))
        {
            if (Enum.IsDefined(typeof(T), intEnumValue))
            {
                returnValue = (T)(object)intEnumValue;
                return true;
            }
        }
        return false;
    }
    

提交回复
热议问题