Associating Additional Information with .NET Enum

后端 未结 5 1249
轻奢々
轻奢々 2021-02-01 04:51

My question is best illustrated with an example.

Suppose I have the enum:

public enum ArrowDirection
{
    North,
    South,
    East,
    West
}
         


        
5条回答
  •  梦谈多话
    2021-02-01 05:41

    I've blogged about it here.

    Try out something like this with Attributes.

      public enum Status {
    
        [Status(Description = "Not Available")]      
    
        Not_Available = 1,      
    
        [Status(Description = "Available For Game")] 
    
        Available_For_Game = 2,      
    
        [Status(Description = "Available For Discussion")] 
    
        Available_For_Discussion = 3,
    
      }
    
      public class StatusEnumInfo {
    
        private static StatusAttribute[] edesc; 
    
        public static String GetDescription(object e)
    
        {
    
          System.Reflection.FieldInfo f = e.GetType().GetField(e.ToString()); 
    
          StatusEnumInfo.edesc = f.GetCustomAttributes(typeof(StatusAttribute), false) as StatusAttribute[]; 
    
          if (StatusEnumInfo.edesc != null && StatusEnumInfo.edesc.Length == 1)         
    
            return StatusEnumInfo.edesc[0].Description; 
    
          else         
    
            return String.Empty;
    
        } 
    
        public static object GetEnumFromDesc(Type t, string desc)
    
        {
    
          Array x = Enum.GetValues(t); 
    
          foreach (object o in x) {
    
            if (GetDescription(o).Equals(desc)) {
    
              return o;
    
            }
    
          } return String.Empty;
    
        }
    
      }
    
      public class StatusAttribute : Attribute {
    
        public String Description { get; set; }
    
      }
    
    
    
      public class Implemenation {
    
        public void Run()
    
        {
    
          Status statusEnum = (Status)StatusEnumInfo.GetEnumFromDesc(typeof(Status), "Not Available"); 
    
          String statusString = StatusEnumInfo.GetDescription(Status.Available_For_Discussion);
    
        }
    
      }
    

    Instead of Description, use your custom Property

提交回复
热议问题