有时候,我们需要针对枚举与字符之间做相应转换,这个时候我们可以通过反射获取Enum对应的字段属性进行转换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace ConsoleApp1
{
//枚举类型转换
public static class EnumConvert
{
//int -> enum
public static T EnumFromInt<T>(int Val)
{
T Ret = default(T);
try
{
Ret = (T)Enum.ToObject(typeof(T), Val);
}
catch (System.Exception)
{
return default(T);
}
return Ret;
}
//string -> enum
public static T EnumFromString<T>(string Val)
{
T Ret = default(T);
try
{
Ret = (T)Enum.Parse(typeof(T), Val);
}
catch (System.Exception)
{
return default(T);
}
return Ret;
}
// enum -> int 直接隐式转换(int)Enum
// enum -> string
public static string EnumToString<T>(T Val)
{
return Enum.GetName(typeof(T), Val);
}
// enum -> string
public static string EnumToString<T>(this System.Enum en, T Val)
{
return Enum.GetName(typeof(T), Val);
}
//Enum项目中增加[Description("描述")],使用此函数获取此值
public static string GetEnumDescription(System.Enum value)
{
string output = null;
System.Type type = value.GetType();
System.Reflection.FieldInfo fi = type.GetField(value.ToString());
DescriptionAttribute[] attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
if (attrs.Length > 0)
{
output = attrs[0].Description;
}
return output;
}
}
}
程序测试:
class Program
{
static void Main(string[] args)
{
string place = EnumConvert.GetEnumDescription(ePlace.GZ);
Console.WriteLine("place={0}", place);
ePlace ep = EnumConvert.EnumFromInt<ePlace>(2);
Console.WriteLine("ep={0}", ep.ToString());
string p = EnumConvert.EnumToString<ePlace>(ePlace.GZ);
Console.WriteLine("p={0}", p);
}
}
public enum ePlace
{
[Description("Beijing")]
BJ,
[Description("Shanghai")]
SH,
[Description("Guangzhou")]
GZ,
[Description("Shenzhen")]
SZ,
}
运行结果: