C#枚举显示汉字
标签:== lse null pac 它的 nat com menu map
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.ComponentModel;
namespace EnumApp
{
class Program
{
static void Main(string[] args)
{
NameValueCollection nvc = GetNVCFromEnumValue(typeof(TimeOfDay));
foreach (string key in nvc.Keys)
{
Console.WriteLine(string.Format(key + ": {0}", nvc[key]));
}
Dictionary dic = GetEnumDic(typeof(TimeOfDay));
foreach(string key in dic.Keys)
{
Console.WriteLine(key+":{0}",dic[key]);
}
Console.WriteLine(string.Format(TimeOfDay.Moning.ToString() + ":{0}", GetEnumDes(TimeOfDay.Moning)));
}
///
/// 从枚举类型和它的特性读出并返回一个键值对
///
/// Type,该参数的格式为typeof(需要读的枚举类型)
/// 键值对
public static NameValueCollection GetNVCFromEnumValue(Type enumType)
{
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(strValue,strText);
}
}
return nvc;
}
///
/// 返回 Dic
///
///
/// Dic
public static Dictionary GetEnumDic(Type enumType)
{
Dictionary dic = new Dictionary();
FieldInfo[] fieldinfos = enumType.GetFields();
foreach (FieldInfo field in fieldinfos)
{
if (field.FieldType.IsEnum)
{
Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
dic.Add(field.Name, ((DescriptionAttribute)objs[0]).Description);
}
}
return dic;
}
///
/// 获得某个枚举项的描述
///
///
///
public static string GetEnumDes(object value)
{
FieldInfo fieldinfo = value.GetType().GetField(value.ToString());
Object[] objs = fieldinfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (objs == null || objs.Length == 0)
{
return value.ToString();
}
else
{
return ((DescriptionAttribute)objs[0]).Description;
}
}
}
public enum TimeOfDay
{
[Description("上午")]
Moning=0,
[Description("下午")]
Afternoon,
[Description("晚上")]
Evening,
};
public enum TimeOfDays
{
上午,
下午,
晚上
};
}
C#枚举显示汉字
标签:== lse null pac 它的 nat com menu map
原文地址:https://www.cnblogs.com/xl4ng/p/12552851.html
文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
文章标题:
C#枚举显示汉字
文章链接:http://soscw.com/essay/64000.html
评论