用字符串值枚举和价值发现枚举 [英] Enums with string values and finding enum by value

查看:164
本文介绍了用字符串值枚举和价值发现枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个枚举像下面,然后有一个方法类似Util.FindFruitByValue(A),它返回枚举苹果。这是因为缩写都存储在数据库中,我需要从数据库读取后,将它们转换为相应的枚举。这可能还是我需要创建一个单独的类呢?请告诉我。先谢谢了。

I want to have an enum like the following and then have a method something like Util.FindFruitByValue("A") which returns the enum Apple. this is because the abbreviations are stored in database and I need to convert them to appropriate enums after reading from db. is this possible OR do I need to create a separate class for it? Please let me know. thanks in advance.

public enum Fruit
{
    Apple = "A"
    Banana = "B"
    Cherry = "C"
}

更新:此就像一个查找表,但不同的是该值是字符串,而不是一个int。我填充的业务对象,通过读取数据库中的值,我想用一种固定的值对象的属性,而不是字符串。

Update: this is like a lookup table, but the difference is the value is string instead of an int. I am populating a business object, by reading the values from database and I would like to use a type with fixed values for the object property instead of string.

推荐答案

我使用的枚举Description属性解决了这个问题。该解决方案如下。我使用扩展方法来获得描述。获得描述代码是从这个链接 HTTP拍摄://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx 。感谢您的答复。

I solved the problem by using the Description attribute on the enum. the solution is as follows. I use the extension method to get the description. the code to get the description is taken from this link http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx. thanks for your replies.

    public enum Fruit
{
    [Description("Apple")]
    A,
    [Description("Banana")]
    B,
    [Description("Cherry")]
    C
}

public static class Util
{
    public static T StringToEnum<T>(string name)
    {
        return (T)Enum.Parse(typeof(T), name);
    }

    public static string ToDescriptionString(this Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
}

这篇关于用字符串值枚举和价值发现枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆