c#中的枚举(enum)

来源:互联网 发布:真实的乌克兰 知乎 编辑:程序博客网 时间:2024/05/16 01:41

1.简介

c#中使用enum关键字用于声明枚举类型,即一种由一组称为枚举数列表的命名常量组成的独特类型,一个简单的例子
enum Days{Mon, Tue, Wed, Thu, Fri,Sat, Sun};//采用默认方式
enum Days:byte{Mon=1, Tue, Wed, Thu, Fri,Sat, Sun};//自定义方式
几点说明
1>枚举元素的默认基础类型为 int,第一个枚举数的值为 0,后面每个枚举数的值依次递增 1
2>每种枚举类型都有基础类型,该类型可以是除 char 以外的任何整型,有byte、sbyte、short、ushort、int、uint、long 和 ulong
3>枚举可以嵌套在类或结构中,还可以在命名空间内直接定义枚举,这样以便该命名空间中的所有类都能够同样方便地访问它

2.常见使用

1>获取单个枚举元素名字

public class Program {
    enum Days{Mon, Tue, Wed, Thu, Fri,Sat, Sun};
    public static void Main() {
        Console.WriteLine("The 4th name of the Days Enum is {0}", Enum.GetName(typeof(Days), 3));//方法1

Console.WriteLine("The 4th name of the Days Enum is {0}", Days.Thu.ToString());//方法2

Console.ReadLine();

    }
}
// The example displays the following output:
//       The 4th name of the Days Enum is Thu
//       The 4th name of the Days Enum is Thu


2>获取所有枚举元素名字

public class Program {
    enum Days{Mon, Tue, Wed, Thu, Fri,Sat, Sun};
    public static void Main() {
foreach (var name in Enum.GetNames(typeof(Days))) {
Console.WriteLine(name);

}

Console.ReadLine();

    }
}
// The example displays the following output:
// Mon
// Tue
// Wed
// Thu
// Fri
// Sat
// Sun

3>获取单个枚举元素值

public class Program {
    enum Days{Mon, Tue, Wed, Thu, Fri,Sat, Sun};
    public static void Main() {

        Console.WriteLine("The 4th value of the Days Enum is {0}", (int)Days.Thu);

Console.ReadLine();

    }
}
// The example displays the following output:
//       The 4th value of the Days Enum is 3

4>获取所有枚举元素值

public class Program {
    enum Days{Mon, Tue, Wed, Thu, Fri,Sat, Sun};
    public static void Main() {
foreach (var name in Enum.GetValues(typeof(Days))) {
Console.WriteLine(name);

}

Console.ReadLine();

    }
}
// The example displays the following output:
// 0
// 1
// 2
// 3
// 4
// 5

// 6

5>将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象,一个参数指定该操作是否不区分大小写

class Program
    {
         enum Days{Mon, Tue, Wed, Thu, Fri,Sat, Sun};
        public static void Main() {
            if (Days.Mon.Equals(Enum.Parse(typeof(Days), "0", true)) && Days.Mon.Equals(Enum.Parse(typeof(Days), "mon", true)))
            {
                Console.WriteLine("true");
            }
            else
            {
                Console.WriteLine("false");
            }
            Console.ReadLine();
        }


    }

//true

0 0
原创粉丝点击