📅  最后修改于: 2020-10-31 03:01:31             🧑  作者: Mango
C#中的枚举也称为枚举。它用于存储一组命名常量,例如季节,天,月,大小等。枚举常量也称为枚举器。 C#中的枚举可以在类和结构内部或外部声明。
枚举常量的默认值从0开始,然后逐一递增。但是我们可以更改默认值。
让我们看一个简单的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);
}
}
输出:
WINTER = 0
SUMMER = 2
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);
}
}
输出:
WINTER = 10
SUMMER = 12
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);
}
}
输出:
Sun = 0
Mon = 1
Sat = 6
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
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