【问题标题】:How to access integer and string of enum type?如何访问枚举类型的整数和字符串?
【发布时间】:2013-04-11 10:56:37
【问题描述】:

对于下面的枚举类型的变量,哪些 C# 代码会输出以下内容?

牙医 (2533)

public enum eOccupationCode
        {
             Butcher = 2531,
             Baker = 2532,
             Dentist = 2533,
             Podiatrist = 2534,
             Surgeon = 2535,
             Other = 2539
        }

【问题讨论】:

    标签: c# .net string enums


    【解决方案1】:

    听起来你想要这样的东西:

    // Please drop the "e" prefix...
    OccupationCode code = OccupationCode.Dentist;
    
    string text = string.Format("{0} ({1})", code, (int) code);
    

    【讨论】:

    • 是的,他真的应该去掉“e”前缀
    【解决方案2】:

    您还可以使用format stringsgGfF 打印枚举条目的名称,或使用dD 打印十进制表示:

    var dentist = eOccupationCode.Dentist;
    
    Console.WriteLine(dentist.ToString("G"));     // Prints: "Dentist"
    Console.WriteLine(dentist.ToString("D"));     // Prints: "2533"
    

    ... 或作为方便的单线:

    Console.WriteLine("{0:G} ({0:D})", dentist);  // Prints: "Dentist (2533)"
    

    这适用于Console.WriteLine,就像String.Format一样。

    【讨论】:

      【解决方案3】:

      What C# code would output the following for a variable of the enum type below?

      如果不进行强制转换,它将输出枚举标识符:Dentist

      如果您需要访问该枚举值,则需要对其进行强制转换:

      int value = (int)eOccupationCode.Dentist;
      

      【讨论】:

      • 你能帮忙解释一下为什么这是默认值并且使用枚举值不是默认值吗?
      【解决方案4】:

      我猜你的意思是这个

      eOccupationCode code = eOccupationCode.Dentist;
      Console.WriteLine(string.Format("{0} ({1})", code,(int)code));
      // outputs Dentist (2533)
      

      【讨论】:

      • ToString 是多余的。
      猜你喜欢
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2018-10-23
      相关资源
      最近更新 更多