简体   繁体   中英

How to return a Enum value from a string?

I'm trying to return a strongly typed Enumeration value from a string. I'm sure there is a better way to do this. This just seems like way too much code for a simple thing like this:

    public static DeviceType DefaultDeviceType
    {
        get
        {
            var deviceTypeString = GetSetting("DefaultDeviceType");
            if (deviceTypeString.Equals(DeviceType.IPhone.ToString()))
                return DeviceType.IPhone;
            if (deviceTypeString.Equals(DeviceType.Android.ToString()))
                return DeviceType.Android;
            if (deviceTypeString.Equals(DeviceType.BlackBerry.ToString()))
                return DeviceType.BlackBerry;
            if (deviceTypeString.Equals(DeviceType.Other.ToString()))
                return DeviceType.Other;
            return DeviceType.IPhone; // If no default is provided, use this default.
        }
    }

Ideas?

Based on the feedback I got from the community, I have decided to use a method extension that converts a string to an enumeration. It takes one parameter (the default enumeration value). That default also provides the type, so the generic can be inferred and doesn't need to be specified explicitly using <>. The method is now shortened to this:

    public static DeviceType DefaultDeviceType
    {
        get
        {
            return GetSetting("DefaultDeviceType").ToEnum(DeviceType.IPhone);
        }
    }

Very cool solution that can be reused in the future.

Use Enum.Parse() :

var deviceTypeString = GetSetting("DefaultDeviceType");
return (DeviceType)Enum.Parse( typeof(DeviceType), deviceTypeString );

If the input is unreliable, you should take care, because you will get a ArgumentException if the value can't be interpreted as one of the values of the enum.

There's also an overload of Parse() that allows you to ignore case when making this conversion, if needed.

If you're dealing with (unreliable) user input, I like to use an extension method that permits a default value. Try it out.

    public static TResult ParseEnum<TResult>(this string value, TResult defaultValue)
    {
        try
        {
            return (TResult)Enum.Parse(typeof(TResult), value, true);
        }
        catch (ArgumentException)
        {
            return defaultValue;
        }
    }

I wrote this extension method once to convert to any any enum type from string, this way you don't have to write the conversion code over and over again:

    public static class StringExtensions
    {

    public static T ConvertToEnum<T>(this string value)
    {
        //Guard condition to not allow this to be used with any other type than an Enum
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new InvalidCastException(string.Format("ConvertToEnum does not support converting to type of [{0}]", typeof(T)));
        }


        if (Enum.IsDefined(typeof(T), value) == false)
        {
            //you can throw an exception if the string does not exist in the enum
            throw new InvalidCastException();

            //If you prefer to return the first available enum as the default value then do this
           Enum.GetNames(typeof (T))[0].ConvertToEnum<T>(); //Note: I haven't tested this
        }
        return (T)Enum.Parse(typeof(T), value);
    }
}

To actually use it you can do this:

//This is a enumeration for testing
enum MyEnumType
{
    ENUM1,
    ENUM2
}

//How to cast
var myEnum = "ENUM2".ConvertToEnum<MyEnumType>();

myEnum at this point should equal ENUM2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM