C# Getting Enum values

后端 未结 11 1198
深忆病人
深忆病人 2020-12-12 15:25

I have a enum containing the following (for example):

  • UnitedKingdom,
  • UnitedStates,
  • France,
  • Portugal

In my code I use

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 15:38

    One other possibility that hasn't been mentioned is something like this:

    public class Country
    {
        public static readonly Country UnitedKingdom = new Country("UK");
        public static readonly Country UnitedStates = new Country("US");
        public static readonly Country France = new Country("FR");
        public static readonly Country Protugal = new Country("PT");
    
        private Country(string shortName)
        {
            ShortName = shortName;
        }
    
        public string ShortName { get; private set; }
    }
    

    From this point you could add more properties, but beware of how much you add to the class, and how many static members you add, as the memory bloat it adds could make it not worth it.

    I don't think there are many cases where this strategy is the best approach, but it is an option to be aware of when attempting to add properties or attributes to something you want to be able to treat as essentially an enum.

提交回复
热议问题