How to get C# Enum description from value?

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 (eg 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);

C#中enum的默认底层数据类型是int ,您可以将其转换为int


I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:

string description = Enums.GetDescription((MyEnum)value);

This:

  • Ensures (with generic type constraints) that the value really is an enum value
  • Avoids the boxing in your current solution
  • Caches all the descriptions to avoid using reflection on every call
  • Has a bunch of other methods, including the ability to parse the value from the description
  • I realise the core answer was just the cast from an int to MyEnum , but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)


    I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects:

    public static string DescriptionAttr<T>(this T source)
    {
        FieldInfo fi = source.GetType().GetField(source.ToString());
    
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute), false);
    
        if (attributes != null && attributes.Length > 0) return attributes[0].Description;
        else return source.ToString();
    }
    

    Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this:

    string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
    string classDesc = myInstance.SomeProperty.DescriptionAttr();
    
    链接地址: http://www.djcxy.com/p/16276.html

    上一篇: 如何将枚举转换为C#中的列表?

    下一篇: 如何从值中获取C#Enum描述?