如何从价值得到C#枚举描述? [英] How to get C# Enum description from value?

查看:169
本文介绍了如何从价值得到C#枚举描述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  获取枚举值属性


我有说明一个enum属性是这样的:

 公共枚举MyEnum
{
    名1 = 1,
    [说明(这里是另一个)]
    HereIsAnother = 2,
    [说明(最后一)]
    LastOne = 3
}

我发现code的该位检索基于一个枚举说明

 公共静态字符串GetEnumDescription(枚举值)
{
    字段信息网络= value.GetType()getfield命令(value.ToString());    DescriptionAttribute [] =属性
        (DescriptionAttribute [])fi.GetCustomAttributes(
        typeof运算(DescriptionAttribute)
        假);    如果(属性= NULL&放大器;!&安培;
        attributes.Length> 0)
        返回属性[0]。说明;
    其他
        返回value.ToString();
}

这让我写code,如:

  VAR myEnumDescriptions =从MyEnum n的Enum.GetValues​​(typeof运算(MyEnum))
                         选择新的{ID =(int)的N,名称= Enumerations.GetEnumDescription(N)};

我想要做的是,如果我知道枚举值(例如1) - 我怎样才能找回描述?换句话说,我怎么可以转换为整数到枚举值传递给我的GetDescription方法?


解决方案

  int值= 1;
字符串描述= Enumerations.GetEnumDescription((MyEnum)值);

在C#中的枚举默认的基本数据类型是 INT ,你可以施放它。

Possible Duplicate:
Getting attributes of Enum’s value

I have an enum with Description attributes like this:

public enum MyEnum
{
    Name1 = 1,
    [Description("Here is another")]
    HereIsAnother = 2,
    [Description("Last one")]
    LastOne = 3
}

I found this bit of code for retrieving the description based on an Enum

public static string GetEnumDescription(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();
}

This allows me to write code like:

var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
                         select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };

What I want to do is if I know the enum value (e.g. 1) - how can I retrieve the description? In other words, how can I convert an integer into an "Enum value" to pass to my GetDescription method?

解决方案

int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);

The default underlying data type for an enum in C# is an int, you can just cast it.

这篇关于如何从价值得到C#枚举描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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