c#枚举练习

C#枚举练习:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnumTest
{
enum Color
{
red = 1,
green = 2,
black = 3,
white = 4,
}
class Program
{
static void Main(string[] args)
{
getEnumName(typeof(Color), "red");
getEnumValue(typeof(Color), "red");
}
/// <summary>
/// 传入一个变量获取枚举的名称
/// </summary>
static void getEnumName(Type enumType,string name)
{
if (foreachEnumHasName(enumType,name))
{
//方法1:变量获取枚举的名称
Object obj = Enum.Parse(enumType, name);
Console.WriteLine("枚举名称=" + obj);
Console.ReadKey();
}
else
{
Console.WriteLine("字符串{0} 无效", name);
}
}
/// <summary>
/// 传入一个变量获取枚举的值
/// </summary>
/// <param name="enumStr"></param>
static void getEnumValue(Type enumType,string enumStr)
{
if (foreachEnumHasName(enumType, enumStr))
{
Color color = (Color)Enum.Parse(enumType, enumStr);
//方法1: 获取枚举的值
int colorValue1 = (int)color;
Console.WriteLine(colorValue1);
//方法2:获取枚举的值
int colorValue2 = Convert.ToInt32(color);
Console.WriteLine(colorValue2);
Console.ReadKey();
}
else
{
Console.WriteLine("字符串{0} 无效", enumStr);
Console.ReadKey();
return;
}
}
/// <summary>
/// 遍历枚举
/// </summary>
static bool foreachEnumHasName(Type enumType,string name)
{
foreach (string enumName in Enum.GetNames(enumType))
{
if (name.Equals(enumName))
{
return true;
}
}
return false;
}
}
}