enum的操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
namespace enumkey
{
class Program
{
static void Main(string[] args)
{
Type enumType = typeof(TimeOfDay);
string txt = string.Empty;
foreach (int i in Enum.GetValues(typeof(TimeOfDay)))
txt += i.ToString();
string names=string.Empty;
foreach (string temp in Enum.GetNames(typeof(TimeOfDay)))
names+= temp;
Styles styles = Styles.ShowBorder | Styles.ShowCaption;
NameValueCollection nvc = new NameValueCollection();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.FieldInfo[] fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
DescriptionAttribute aa = (DescriptionAttribute)arr[0];
strText = aa.Description;
}
else
{
strText = field.Name;
}
nvc.Add(strText, strValue);
}
}
}
/// <summary>
/// 从枚举类型和它的特性读出并返回一个键值对
/// </summary>
/// <param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
/// <returns>键值对</returns>
[Flags]
enum Styles{
ShowBorder = 1, //是否显示边框
ShowCaption = 2, //是否显示标题
ShowToolbox = 4 //是否显示工具箱
}
public enum TimeOfDay
{
[Description("上午")]
Moning,
[Description("下午")]
Afternoon,
[Description("晚上")]
Evening,
};
}
}