个性化阅读
专注于IT技术分析

C#枚举

C#中的枚举也称为枚举。它用于存储一组命名常量,例如季节,天,月,大小等。枚举常量也称为枚举器。 C#中的枚举可以在类和结构内部或外部声明。

枚举常量的默认值从0开始,然后逐一递增。但是我们可以更改默认值。

要记住的要点

  • 枚举具有固定的常量集
  • 枚举可提高类型安全性
  • 枚举可以遍历

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);
    }
}

输出:

WINTER = 0
SUMMER = 2

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);
    }
}

输出:

WINTER = 10
SUMMER = 12

Days的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);
    }
}

输出:

Sun = 0
Mon = 1
Sat = 6

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
赞(0)
未经允许不得转载:srcmini » C#枚举

评论 抢沙发

评论前必须登录!