C# 枚举
C# 枚举
C# 中的枚举也称为枚举。它用于存储一组命名常量,例如季节、天、月、大小等。枚举常量也称为枚举数。 C#中的枚举可以在类和结构内部或外部声明。
枚举常量具有从0开始并一一递增的默认值。但是我们可以更改默认值。
要记住的要点
enum 有一组固定的常量
enum 提高了类型安全性
枚举可以遍历
C#枚举示例
我们来看一个简单的C#枚举示例。
using System;
public class EnumExample
{
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void Main()
{
int x = (int)Season.WINTER;
int y = (int)Season.SUMMER;
Console.WriteLine("WINTER = {0}", x);
Console.WriteLine("SUMMER = {0}", y);
}
}
输出:
C# 枚举示例更改起始索引
using System;
public class EnumExample
{
public enum Season { WINTER=10, SPRING, SUMMER, FALL }
public static void Main()
{
int x = (int)Season.WINTER;
int y = (int)Season.SUMMER;
Console.WriteLine("WINTER = {0}", x);
Console.WriteLine("SUMMER = {0}", y);
}
}
输出:
C# 天数枚举示例
using System;
public class EnumExample
{
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
public static void Main()
{
int x = (int)Days.Sun;
int y = (int)Days.Mon;
int z = (int)Days.Sat;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Mon = {0}", y);
Console.WriteLine("Sat = {0}", z);
}
}
输出:
C# 枚举示例: 使用 getNames() 遍历所有值
using System;
public class EnumExample
{
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
public static void Main()
{
foreach (string s in Enum.GetNames(typeof(Days)))
{
Console.WriteLine(s);
}
}
}
输出:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
C# 枚举示例: 使用 getValues() 遍历所有值
using System;
public class EnumExample
{
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
public static void Main()
{
foreach (Days d in Enum.GetValues(typeof(Days)))
{
Console.WriteLine(d);
}
}
}
输出:
Sun
Mon
Tue
Wed
Thu
Fri
Sat