C# Getting Enum values

后端 未结 11 1175
深忆病人
深忆病人 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:50

    You could create an extension method public static string ToShortString(this Country country). In the method you could use either a static Dictionary as Jon suggests, or you could simply do a switch case.

    Example:

    public static class CountryExtensions
    {
        public static string ToShortString( this Country target )
        {
            switch (target) {
                case Country.UnitedKingdom:
                    return "UK";
                case Country.UnitedStates:
                    return "US";
                case Country.France:
                    return "FR";
                case Country.Portugal:
                    return "PT";
                default:
                    return "None";
            }
        }
    }
    

提交回复
热议问题