2012-10-24 51 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? –