Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C# 枚举


C# 枚举

一个 enum 是一种特殊的“类”,它表示一组**常量**(不可更改/只读变量)。

要创建一个 enum,请使用 enum 关键字(而不是 class 或 interface),并用逗号分隔枚举项

示例

enum Level 
{
  Low,
  Medium,
  High
}

您可以使用**点**语法访问 enum

Level myVar = Level.Medium;
Console.WriteLine(myVar);
自己试试 »

Enum 是“枚举”的缩写,意思是“具体列出”。


类中的枚举

您也可以在类中包含一个 enum

示例

class Program
{
  enum Level
  {
    Low,
    Medium,
    High
  }
  static void Main(string[] args)
  {
    Level myVar = Level.Medium;
    Console.WriteLine(myVar);
  }
}

输出将是

中等
自己试试 »


枚举值

默认情况下,枚举的第一个项目的值为 0。第二个值为 1,依此类推。

要获取项目的整数值,您必须显式转换该项目为 int

示例

enum Months
{
  January,    // 0
  February,   // 1
  March,      // 2
  April,      // 3
  May,        // 4
  June,       // 5
  July        // 6
}

static void Main(string[] args)
{
  int myNum = (int) Months.April;
  Console.WriteLine(myNum);
}

输出将是

3
自己试试 »

您还可以分配自己的枚举值,并且后续项目将相应更新其数字

示例

enum Months
{
  January,    // 0
  February,   // 1
  March=6,    // 6
  April,      // 7
  May,        // 8
  June,       // 9
  July        // 10
}

static void Main(string[] args)
{
  int myNum = (int) Months.April;
  Console.WriteLine(myNum);
}

输出将是

7
自己试试 »

Switch 语句中的枚举

枚举通常用于 switch 语句中以检查相应的 value 值

示例

enum Level 
{
  Low,
  Medium,
  High
}

static void Main(string[] args) 
{
  Level myVar = Level.Medium;
  switch(myVar) 
  {
    case Level.Low:
      Console.WriteLine("Low level");
      break;
    case Level.Medium:
       Console.WriteLine("Medium level");
      break;
    case Level.High:
      Console.WriteLine("High level");
      break;
  }
}

输出将是

中等水平
自己试试 »

为什么要以及何时使用枚举?

当您拥有知道不会更改的值时使用枚举,例如月份、星期几、颜色、一副牌等。

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.