2009-10-22 102 views
2

我正在尋找一個開源庫或用於在.Net中使用Enum類型的示例。除了人們用於Enums(TypeParse等)的標準擴展之外,我還需要一種方法來執行操作,例如爲給定的枚舉值返回Description屬性的值或返回具有Description屬性值的枚舉值匹配給定的字符串。枚舉實用程序庫

例如:

//if extension method 
var race = Race.FromDescription("AA") // returns Race.AfricanAmerican 
//and 
string raceDescription = Race.AfricanAmerican.GetDescription() //returns "AA" 
+1

還有全碟庫通用枚舉類型約束: http://code.google.com/p/unconstrained-melody/ – TrueWill 2009-10-22 17:32:57

+0

第一部分是http://stackoverflow.com/questions/17772/anyone-know-a-quick-way-對獲得到自定義屬性上-AN-枚舉值。 – nawfal 2013-06-09 11:59:15

回答

2

如果沒有的話,就一個!你可以在Stackoverflow上找到你需要的其他答案,只需把它們放到一個項目中即可。這裏有幾個讓你開始:

Getting value of enum Description:

public static string GetDescription(this Enum value) 
{ 
    FieldInfo field = value.GetType().GetField(value.ToString()); 
    object[] attribs = field.GetCustomAttributes(typeof(DescriptionAttribute), true)); 
    if(attribs.Length > 0) 
    { 
     return ((DescriptionAttribute)attribs[0]).Description; 
    } 
    return string.Empty; 
} 

Getting a nullable enum value from string:

public static class EnumUtils 
{ 
    public static Nullable<T> Parse<T>(string input) where T : struct 
    { 
     //since we cant do a generic type constraint 
     if (!typeof(T).IsEnum) 
     { 
      throw new ArgumentException("Generic Type 'T' must be an Enum"); 
     } 
     if (!string.IsNullOrEmpty(input)) 
     { 
      if (Enum.GetNames(typeof(T)).Any(
        e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant())) 
      { 
       return (T)Enum.Parse(typeof(T), input, true); 
      } 
     } 
     return null; 
    } 
} 
3

我看了這個博客張貼關於使用類而不是枚舉的一天:

http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx

建議使用抽象類作爲枚舉類的基礎。基類有東西一樣平等,分析,比較等

使用它,你可以有你的枚舉像這樣的(例如,從文章所)類:

public class EmployeeType : Enumeration 
{ 
    public static readonly EmployeeType Manager 
     = new EmployeeType(0, "Manager"); 
    public static readonly EmployeeType Servant 
     = new EmployeeType(1, "Servant"); 
    public static readonly EmployeeType AssistantToTheRegionalManager 
     = new EmployeeType(2, "Assistant to the Regional Manager"); 

    private EmployeeType() { } 
    private EmployeeType(int value, string displayName) : base(value, displayName) { } 
} 
+0

謝謝你的問候。文章提出了一些與我的情況相關的非常好的觀點。 – 2009-10-22 15:40:04