枚举带有字符串值并通过值查找枚举 [英] Enums with string values and finding enum by value

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

问题描述

我想要一个像下面这样的枚举,然后有一个方法,如Util.FindFruitByValue(A),它返回枚举苹果。这是因为缩写存储在数据库中,我需要在从db读取数据之后将其转换为适当的枚举。这是可能OR还是需要为它创建一个单独的类?请告诉我。感谢提前。

  public enum Fruit 
{
Apple =A
香蕉=B
Cherry =C
}

更新:就像一个查找表,不同之处在于值是string而不是int。我正在填充一个业务对象,通过读取数据库中的值,我想使用一个具有固定值的对象属性而不是字符串的类型。

解决方案

我使用枚举中的描述属性解决了问题。解决方案如下。我使用扩展方法来获取描述。获取描述的代码取自此链接 http://blog.spontaneouspublicity.com/post/2008/01/17/Associating-Strings-with-enums-in-C.aspx 。感谢您的答复。

  public enum Fruit 
{
[Description(Apple)]
A,
[描述(香蕉)]
B,
[描述(樱桃)]
C
}

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

public static string ToDescriptionString(此枚举值)
{
FieldInfo fi = value.GetType()。GetField(value.ToString());

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

if(attributes!= null&&
attributes.Length> 0)
返回属性[0] .Description;
else
返回值.ToString();
}
}


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

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.

解决方案

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天全站免登陆