2012-10-24 52 views
2

可能重复:
Enum ToString如何获取Enum描述的字符串列表?

我怎样才能得到一个枚举的值的列表?

例如,我有以下几点:

public enum ContactSubjects 
{ 
    [Description("General Question")] 
    General, 
    [Description("Availability/Reservation")] 
    Reservation, 
    [Description("Other Issue")] 
    Other 
} 

我需要能够做的是通过ContactSubject.General作为参数,它返回的说明的列表。

此方法需要与任何枚举,而不仅仅是ContactSubject(在我的例子中)。签名应该像GetEnumDescriptions(枚举值)。

+1

嗨,那些似乎不是我的问题的答案。我需要列出所有基础枚举值。我可以得到一个单独的枚举的描述,或者如果我明确知道类型,而不是简单地传递Enum值。 – kodikas

+0

啊,我明白你的意思了。你不能调用不仅仅是在其他答案中的代码,而是传入你的value.GetType()类型? –

回答

5

类似的东西可能工作:

private static IEnumerable<string> GetDescriptions(Type type) 
    { 
     var descs = new List<string>(); 
     var names = Enum.GetNames(type); 
     foreach (var name in names) 
     { 
      var field = type.GetField(name); 
      var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true); 
      foreach (DescriptionAttribute fd in fds) 
      { 
       descs.Add(fd.Description); 
      } 
     } 
     return descs; 
    } 

但是你可以查看一些逻辑存在:如是否确定要开始的名字?你将如何处理多个Description属性?如果他们中的一些人失踪了 - 你想要一个名字还是只是像上面那样跳过它?等

刚刚审查您的问题。对于VALUE你会有这样的事情:

private static IEnumerable<string> GetDescriptions(Enum value) 
{ 
    var descs = new List<string>(); 
    var type = value.GetType(); 
    var name = Enum.GetName(type, value); 
    var field = type.GetField(name); 
    var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true); 
    foreach (DescriptionAttribute fd in fds) 
    { 
     descs.Add(fd.Description); 
    } 
    return descs; 
} 

但它是不可能将两个说明单字段属性,所以我想它可能会返回字符串只。

+0

如何使用DropDownListFor? –