枚举中包含的打印常量

时间:2016-01-13 01:51:20

标签: c# enums

public struct RollerCoasterInfo
{
    public string Name;
    public RollerCoasterType Type;
}

public enum RollerCoasterType
{
    Wooden,
    Steel,
    Hyper,
    Heartline,
    VirginiaReel,
    Mine,
    Suspeneded,
}
class RollerCoasterProgram
{
    static void Main(string[] args)
    {
        RollerCoasterInfo rc1;
        Console.WriteLine("Please Enter The Following Information");
        Console.Write("Name of the Rollercoaster: ");
        rc1.Name = Console.ReadLine();
        Console.Write("Type of rollecoaster {0} is", rc1.Name);
        ...
    }
}

如何打印枚举Rollercoastertype中的所有常量,看起来如下所示?

  
      
  1.   
  2.   
  3.   
  4. ETC ...
  5.   

3 个答案:

答案 0 :(得分:2)

试试这个:

   //All enums
    var x = Enum.GetValues(typeof(RollerCoasterType));
    foreach(var item in x)
        Console.WriteLine("{0} - {1}",(int)item,item);

    //Just names
    var names = Enum.GetNames(typeof(RollerCoasterType));       
    foreach(var name in names)
        Console.WriteLine(name);

看到它在我的小提琴中工作:https://dotnetfiddle.net/AIGl6M

  

注意:

     
      
  • Enum.GetValues:将获取enum中的所有值,例如Enum.GetValues(typeof(RollerCoasterType))将返回数组RollerCoasterType[];
  •   
     
    
        
  • Enum.GetNames:将从枚举中获取所有值名称,例如Enum.getNames(typeof(RollerCoasterType))将返回数组string[];
  •     
  

答案 1 :(得分:0)

使用

byte[]

'3'这里是元素索引。

答案 2 :(得分:0)

另一种方式是:

var _values = Enum.GetValues(typeof(Rollercoastertype )).Cast<Rollercoastertype >();

这是一个显示所有这些答案之间差异的链接:Enum.GetValue与Enum.GetName:Difference between Enum.GetValues and Enum.GetNames

相关问题