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
- c#中的枚举(enum)
- C#中的enum枚举类
- C#中的枚举类型(enum type)
- C#枚举类型enum
- C#枚举类型enum
- C#枚举类型enum
- C# Enum (枚举)
- c# 枚举 enum
- c# 枚举 enum 类型
- C# Enum (枚举)
- C#枚举遍历--Enum
- C# 枚举(Enum)
- c#枚举enum
- C#梳理【枚举Enum】
- C#枚举类型-Enum
- c# enum 枚举
- java 中的enum(枚举)
- Java中的枚举Enum
- SharedPreferences用法
- 浅谈 Python 程序和 C 程序的整合
- Java基础18--泛型--工具类--JDK1.5新特性
- c#中的类 对象和实例
- ViewPager导航或翻页入门
- c#中的枚举(enum)
- sift是图像匹配的非常经典的算法
- 项目视频讲解_国家电力项目实战
- C.Interface.And.Implementations—table(key-value系统)的实现
- c#类不允许直接new出对象
- javaScript操作option的添加删除
- 几个概念
- c#new 对象过程探析
- 运行地址和加载地址