2011-02-08 39 views
8

Tôi có thể có enum hoạt động như một cặp giá trị khóa hay không.Cặp giá trị chính như enum

public enum infringementCategory 
{ 
    Infringement, 
    OFN 
} 

Nếu tôi chọn Infringement tôi nên nhận được "INF0001" và nếu tôi chọn OFN tôi nên nhận được "INF0002"

Có thể?

+0

thể trùng lặp của [C# Chuỗi enums] (http://stackoverflow.com/questions/424366/c-sharp-string-enums) – nawfal

+0

Enum không phải là một lựa chọn tốt trong trường hợp của bạn, sử dụng từ điển để thay thế. –

Trả lời

5

Bạn có thể sử dụng trang trí để liên kết chuỗi đại diện với các giá trị enum của bạn. Kiểm tra câu hỏi này: Enum ToString with user friendly strings

Nó sẽ giống như:

public enum infringementCategory 
{ 
    [Description("INF0001")] 
    Infringement, 
    [Description("INF0002")] 
    OFN 
} 

Trông gọn gàng hơn so với sử dụng từ điển và cần ít duy trì.

2

Bạn có thể lưu trữ các chức danh (INF0001) ... trong một Dictionary<infringementCategory, string>

3

Cập nhật:
Nhờ Oliver đã chỉ ra System.Component.DescriptionAttribute. Dưới đây là làm thế nào để làm điều đó:

public enum infringementCategory 
{ 
    [Description("INF0001")] 
    Infringement, 
    [Description("INF0002")] 
    OFN 
} 

public static class DescriptionExtensions 
{ 
    public static string GetDescriptionValue(this Enum value) 
    { 
     // Get the type 
     Type type = value.GetType(); 

     // Get fieldinfo for this type 
     FieldInfo fieldInfo = type.GetField(value.ToString()); 

     // Get the stringvalue attributes 
     DescriptionAttribute[] attribs = fieldInfo.GetCustomAttributes(
      typeof(DescriptionAttribute), false) as DescriptionAttribute[]; 

     // Return the first if there was a match. 
     return attribs.Length > 0 ? attribs[0].Description : null; 
    } 
} 

public class Program 
{ 
    static void Main(string[] args) 
    { 
     infringementCategory category = infringementCategory.OFN; 
     string description = category.GetDescriptionValue(); 
    } 
} 
+1

Tại sao lại sử dụng thuộc tính tự viết nếu bạn chỉ có thể lấy ['DescriptionAttribute'] (http://msdn.microsoft.com/en-us/library/system.componentmodel.descriptionattribute.aspx)? – Oliver

+0

@Oliver Tôi đồng ý, mặc dù bài đăng trên blog cũng có một phương pháp mở rộng để nhận các giá trị thuộc tính –

-1

Bạn có một số lựa chọn:

  1. Một điển như vc74 gợi ý. Điều này là hiệu quả và decouples enum của bạn từ tài sản.

  2. Một chuyển đổi tuyên bố

  3. Nếu điều duy nhất bạn muốn liên kết với nhau là một số nguyên bạn có thể sử dụng:

    public enum InfringementCategory 
    { 
        Infringement = 1, 
        OFN = 2 
    } 
    

    và sau đó đặt (int)myEnum vào String.Format để biến nó thành một chuỗi các hình thức bạn muốn.

  4. Một Thuộc tính

    public enum InfringementCategory 
    { 
        [InfID("INF0001")]Infringement, 
        [InfID("INF0002")]OFN 
    } 
    

    Đối với cải thiện hiệu suất, bạn có thể sử dụng phản ánh một lần để cư trú từ điển.

7

Làm thế nào về những phần mở rộng:

public static class EnumExtension 
{ 
    /// <summary> 
    /// Gets the string of an DescriptionAttribute of an Enum. 
    /// </summary> 
    /// <param name="value">The Enum value for which the description is needed.</param> 
    /// <returns>If a DescriptionAttribute is set it return the content of it. 
    /// Otherwise just the raw name as string.</returns> 
    public static string Description(this Enum value) 
    { 
     if (value == null) 
     { 
      throw new ArgumentNullException("value"); 
     } 

     string description = value.ToString(); 
     FieldInfo fieldInfo = value.GetType().GetField(description); 
     DescriptionAttribute[] attributes = 
      (DescriptionAttribute[]) 
     fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); 

     if (attributes != null && attributes.Length > 0) 
     { 
      description = attributes[0].Description; 
     } 

     return description; 
    } 

    /// <summary> 
    /// Creates an List with all keys and values of a given Enum class 
    /// </summary> 
    /// <typeparam name="T">Must be derived from class Enum!</typeparam> 
    /// <returns>A list of KeyValuePair&lt;Enum, string&gt; with all available 
    /// names and values of the given Enum.</returns> 
    public static IList<KeyValuePair<Enum, string>> ToList<T>() where T : struct 
    { 
     var type = typeof(T); 

     if (!type.IsEnum) 
     { 
      throw new ArgumentException("T must be an enum"); 
     } 

     return (IList<KeyValuePair<Enum, string>>) 
       Enum.GetValues(type) 
        .OfType<Enum>() 
        .Select(e => new KeyValuePair<Enum, string>(e, e.Description())) 
        .ToArray(); 
    } 

    public static T GetValueFromDescription<T>(string description) where T : struct 
    { 
     var type = typeof(T); 

     if(!type.IsEnum) 
     { 
      throw new ArgumentException("T must be an enum"); 
     } 

     foreach(var field in type.GetFields()) 
     { 
      var attribute = Attribute.GetCustomAttribute(field, 
       typeof(DescriptionAttribute)) as DescriptionAttribute; 

      if(attribute != null) 
      { 
       if(attribute.Description == description) 
       { 
        return (T)field.GetValue(null); 
       } 
      } 
      else 
      { 
       if(field.Name == description) 
       { 
        return (T)field.GetValue(null); 
       } 
      } 
     } 

     throw new ArgumentOutOfRangeException("description"); 
     // or return default(T); 
    } 
} 

Với điều này trong nơi bạn có thể xây dựng được enum của bạn như thế này:

public enum Foo 
{ 
    [Description("Foo - Something")] 
    Something, 
    [Description("Foo - Anything")] 
    Anything, 
} 

Và có được danh sách của bạn như thế này:

var list = EnumExtension.ToList<Foo>(); 
2

Xem:

public enum InfringementCategory 
{ 
    [EnumNamedConstant(Description = "INF0001")] 
    Infringement, 

    [EnumNamedConstant(Description = "INF0002")] 
    OFN 
} 

public class Test{ 
    public void Test() 
    { 
     String result = InfringementCategory.Infringement.GetDescription(); 
    } 
} 

Và tại đây, các phương pháp mở rộng ...

#region [ EnumNamedConstantAttribute ] 
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] 
public class EnumNamedConstantAttribute : Attribute 
{ 
    public string Description { get; set; } 
    public string Value { get; set; } 
} 
#endregion 


#region EnumUtilities 
public static class EnumUtilities 
{ 
    #region [ + Extension Methods ] 

    #region [ GetDescription ] 

    public static string GetDescription(this Enum constant) 
    { 
     return EnumUtilities.GetEnumNamedConstantAttribute(constant).Description; 
    } 
    #endregion 

    #region [ GetStringValue ] 

    public static string GetStringValue(this Enum constant) 
    { 
     return GetEnumNamedConstantValue(constant); 
    } 
    #endregion 

    #endregion 

    #region [ + Static Methods ] 

    #region [ GetEnumerable ] 

    public static IEnumerable<EnumNamedConstantAttribute> GetEnumerable<T>() 
    { 
     T instancia = Activator.CreateInstance<T>(); 

     FieldInfo[] objInfos = instancia.GetType().GetFields(BindingFlags.Public | BindingFlags.Static); 
     foreach (FieldInfo objFileInfo in objInfos) 
     { 
      Enum constant = (Enum)objFileInfo.GetValue(objFileInfo); 
      if (objFileInfo.GetCustomAttributes(typeof(EnumNamedConstantAttribute), false).Length != 0) 
      { 
       yield return new EnumNamedConstantAttribute() 
       { 
        Description = EnumUtilities.GetEnumNamedConstantAttribute(constant).Description, 
        Value = GetEnumNamedConstantValue(constant) 
       }; 
      } 
     } 
    } 
    #endregion 

    #endregion 

    #region [ + Privates ] 

    #region [ GetEnumNamedConstantAttribute ] 
    private static EnumNamedConstantAttribute GetEnumNamedConstantAttribute(Enum constant) 
    { 
     FieldInfo[] objInfos = constant.GetType().GetFields(BindingFlags.Public | BindingFlags.Static); 
     foreach (FieldInfo objFileInfo in objInfos) 
     { 
      Enum constantItem = (Enum)objFileInfo.GetValue(objFileInfo); 
      if (constantItem.GetHashCode().Equals(constant.GetHashCode())) 
      { 
       object[] attributes = objFileInfo.GetCustomAttributes(typeof(EnumNamedConstantAttribute), false); 

       if (attributes.Length > 0) 
        return (EnumNamedConstantAttribute)attributes[0]; 
      } 
     } 
     return null; 
    } 
    #endregion 

    #region [ GetEnumNamedConstantValue ] 
    private static string GetEnumNamedConstantValue(Enum constant) 
    { 
     string sValue = (constant.GetHashCode()).ToString(); 
     EnumNamedConstantAttribute objRet = EnumUtilities.GetEnumNamedConstantAttribute(constant); 
     if (objRet != null) 
     { 
      String sAux = objRet.Value; 
      if (!String.IsNullOrEmpty(sAux)) 
       sValue = objRet.Value; 
     } 
     return sValue; 
    } 
    #endregion 

    #endregion 
} 
#endregion 
Các vấn đề liên quan