C#的Enum——枚举
2009-12-12 11:20
253 查看
c# 枚举实例
[C#]Enum枚举类型使用总结public enum Colors
{
Red = 1,
Green = 2,
Blue = 4,
Yellow =
8
};
The entries of the Colors Enum
are:
Red
Green
Blue
Yellow
根据name获得Enum的类型:
Colors
mycolor =
(Colors)Enum.Parse(typeof(Colors),"red",true);
(int)mycolor1=1
mycolor1.GetTypeCode=Int32
根据value获得Enum的类型:
Colors
mycolor =
(Colors)Enum.Parse(typeof(Colors),"1",true);
mycolor2.ToString()=Red
mycolor2.GetTypeCode=Int32
遍历枚举内容
foreach(string
s in Enum.GetNames(typeof(Colors)))
{
//to do
}
Colors
myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Blue,Yellow");
The
myOrange value has the combined entries of
[myOrange.ToString()]=13
Colors myOrange2 =
(Colors)Enum.Parse(typeof(Colors), "Red, Blue");
The myOrange2 value has the
combined entries of [myOrange2.ToString()]=5
枚举方法
<1>获取枚举字符串
TimeOfDay time
=
TimeOfDay.Afternoon;
Console.WriteLine(time.ToString());
//
输出:Afternoon
<2>Enum.Parse()方法。这个方法带
3
个参数,第一个参数是要使用的枚举类型。其语法是关键字
typeof
后跟放在括号中的枚举类名。
typeof
运算符将在第
5
章详细论述。第二个参数是要转换的字符串,第三个参数是一个
bool
,指定在进行转换时是否忽略大小写。最后,注意
Enum.Parse()
方法实际上返回一个对象引用——
我们需要把这个字符串显式转换为需要的枚举类型
(
这是一个取消装箱操作的例子
)
。对于上面的代码,将返回
1
,作为一个对象,对应于
TimeOfDay.Afternoon
的枚举值。在显式转换为
int
时,会再次生成
1。
TimeOfDay time2
=
(TimeOfDay) Enum.Parse(
typeof
(TimeOfDay),
"
afternoon
"
,
true
);
Console.WriteLine((
int
)time2);
//
输出1
<3>得到枚举的某一值对应的名称
lbOne.Text
=
Enum.GetName(
typeof
(TimeOfDay),
0
);
lbOne.Text
=
((TimeOfDay)
0
).ToString();
//
返回:Morning
两种方法都能实现,但是当其值越界(不是枚举所列出的值),就有一定的区别了。大家可以根据自己的需求不同,选择合适的方法。
lbCon.Text
=
((TimeOfDay)
5
).ToString();
//
返回:5,如果越界返回原值
this
.lbGetName.Text
=
Enum.GetName(
typeof
(TimeOfDay),
5
);
//
返回:空字符串,如果越界返回空字符串
<4>得到枚举的所有的值
foreach
(
int
i
in
Enum.GetValues(
typeof
(TimeOfDay)))
lbValues.Text
+=
i.ToString();
<5>枚举所有的名称
foreach
(
string
temp
in
Enum.GetNames(
typeof
(TimeOfDay)))
lbNames.Text
+=
temp;
相关文章推荐
- C#的Enum——枚举
- C# Enum枚举转 Dictionary字典
- C# Enum枚举转 Dictionary字典
- C# Enum枚举转 Dictionary字典
- C# Enum,Int,String的互相转换 枚举转换
- C# Enum,Int,String的互相转换 枚举转换
- C#enum枚举
- C#枚举enum定义使用
- C#的Enum——枚举
- C#枚举类型enum
- c# 枚举 enum 类型
- C# 枚举(enum)-设计
- C# Enum,Int,String的互相转换 枚举转换
- C#枚举的不常用方法Enum.Parse&Enum.GetNames
- C# 根据Enum 枚举生成下拉列表数据源
- C# 获取枚举 Enum 变量值的 Description 属性
- 关于C#的enum枚举
- C#梳理【枚举Enum】
- C#枚举类型-Enum