C# Getting Enum values

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

    The following solution works (compiles and runs). I see two issues:

    1. You would have to make sure the enums are in sync. (An automated test can do that for you.)

    2. You would be relying in the fact that enums are not type safe in .NET.

      enum Country
      {
          UnitedKingdom = 0,
          UnitedStates = 1,
          France = 2,
          Portugal = 3
      }
      
      enum CountryCode
      {
          UK = 0,
          US = 1,
          FR = 2,
          PT = 3
      }
      
      void Main()
      {
          string countryCode = ((CountryCode)Country.UnitedKingdom).ToString();
          Console.WriteLine(countryCode);
          countryCode = ((CountryCode)Country.Portugal).ToString();
          Console.WriteLine(countryCode);
      }
      

提交回复
热议问题