如何从字符串返回枚举值?

发布于 2024-09-12 00:59:53 字数 1133 浏览 4 评论 0原文

我正在尝试从字符串返回强类型枚举值。我确信有更好的方法来做到这一点。对于像这样的简单事情来说,这似乎是太多的代码:

    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.
        }
    }

想法?

根据从社区获得的反馈,我决定使用将字符串转换为枚举的方法扩展。它采用一个参数(默认枚举值)。该默认值还提供类型,因此可以推断泛型,并且不需要使用 <> 显式指定。该方法现在缩短为:

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

非常酷的解决方案,可以在将来重用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吃兔兔 2024-09-19 00:59:53

使用 Enum.Parse()< /a>:

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

如果输入不可靠,您应该小心,因为如果该值无法解释为枚举的值之一,您将收到 ArgumentException

还有一个 Parse() 的重载,允许您在进行此转换时忽略大小写(如果需要)。

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.

情场扛把子 2024-09-19 00:59:53

如果您正在处理(不可靠的)用户输入,我喜欢使用允许默认值的扩展方法。尝试一下。

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

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;
        }
    }
望笑 2024-09-19 00:59:53

我写了一次这个扩展方法来从字符串转换为任何枚举类型,这样你就不必一遍又一遍地编写转换代码:

    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);
    }
}

要实际使用它,你可以这样做:

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

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

myEnum 此时应该等于 ENUM2

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文