0

我创建了这个枚举

 public enum Days
    {
        [Display("Monday")]
        Mon,
        [Display("Tuesday")]
        Tue,
        [Display("Wednesday")]
        Wed,
        [Display("Thursday")]
        Thu,
        [Display("Friday")]
        Fri,
        [Display("Satrday")]
        Sat,
    }

我想得到字符串“星期一”。我试过这样做

Console.WriteLine(Days.mon);

但是给了我“星期一”而不是“星期一”。有什么方法可以让星期一得到字符串吗?

4

2 回答 2

10

我已经增强了这个答案,为您提供更全面的解决方案,并具有更好的语义语法。

using System;
using System.ComponentModel;

public static class EnumExtensions {

    // This extension method is broken out so you can use a similar pattern with 
    // other MetaData elements in the future. This is your base method for each.
    public static T GetAttribute<T>(this Enum value) where T : Attribute {
        var type = value.GetType();
        var memberInfo = type.GetMember(value.ToString());
        var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
        return (T)attributes[0];
    }

    // This method creates a specific call to the above method, requesting the
    // Description MetaData attribute.
    public static string ToName(this Enum value) {
        var attribute = value.GetAttribute<DescriptionAttribute>();
        return attribute == null ? value.ToString() : attribute.Description;
    }

}

这个解决方案在 Enum 上创建了一对扩展方法,让您可以做您正在寻找的事情。我稍微增强了您的代码Enum,以使用.DisplayAttributeSystem.ComponentModel.DataAnnotations

using System.ComponentModel.DataAnnotations;

    public enum Days {
        [Display(Name = "Sunday")]
        Sun,
        [Display(Name = "Monday")]
        Mon,
        [Display(Name = "Tuesday")]
        Tue,
        [Display(Name = "Wednesday")]
        Wed,
        [Display(Name = "Thursday")]
        Thu,
        [Display(Name = "Friday")]
        Fri,
        [Display(Name = "Saturday")]
        Sat
    }

要使用上述扩展方法,您现在只需调用以下代码:

Console.WriteLine(Days.Mon.ToName());

或者

var day = Days.Mon;
Console.WriteLine(day.ToName());
于 2013-10-27T18:02:11.110 回答
2
var type = typeof(Days);
var memInfo = type.GetMember(Days.Mon.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute),
    false);
var description = ((DisplayAttribute)attributes[0]).Description;

类似于解决方案。

于 2013-10-27T12:01:53.510 回答