Associating Additional Information with .NET Enum

后端 未结 5 1248
轻奢々
轻奢々 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:56

    using System.ComponentModel;
    using System.Reflection;
    
    
    public enum ArrowDirection
    {
    
    [Description("Northwards")]
    North,
    
    [Description("Southwards")]
    South,
    
    [Description("Eastwards")]
    East,
    
    [Description("Westwards")]
    West
    }
    

    ...

    Create an extension method to get a list of descriptions:

    public static class Enum where T : struct
    {
    
        /// 
        /// Gets a collection of the enum value descriptions.
        /// 
        /// 
        public static IList GetDescriptions()
        {
            List descriptions = new List();
            foreach (object enumValue in Enum.GetValues())
            {
                descriptions.Add(((Enum)enumValue).ToDescription());
            }
            return descriptions;
    
        }
    }
    

提交回复
热议问题