枚举:Enum-Int-String之间的转换与扩展
示例枚举:
public enum Color
{
[Description("红色")]
Red,
[Description("绿色")]
Green = 7,
[Description("蓝色")]
Blue
}
Enum转Int
int red = (int)Color.Red;//0
int green = (int)Color.Green;//7
int blue = (int)Color.Blue;//8
- 枚举类型默认为Int
- 枚举值默认从0开始,并依次递增
Int转Enum
Color a = (Color)5;//不报错
Color b = (Color)7;
Console.WriteLine(a.ToString());//5
Console.WriteLine(b.ToString());//Green
- Int 可以直接转 Enum
- 枚举可能会得到非预期的值(值没有对应的成员),不会报错
Enum转String
var red = Color.Red.ToString();//Red
var green = Color.Green.ToString();//Green
var blue = Color.Blue.ToString();//Blue
String转Enum
var green = Enum.Parse(typeof(Color), "Green");//Color.Green
var black = Enum.Parse(typeof(Color), "Black");//throw ArgumentException
Enum.TryParse<Color>("Black", out var blackTry);//Color.Red
- 和枚举名相同的字符可以转成相对应的枚举(区分大小写)
- 转化不存在的字符,会抛出异常(不同于Int)
- 使用Enum.TryParse转换,不存在,则返回默认枚举
- 枚举的默认值 0,即使没有为0的成员
读取Description
当我需要展示枚举 Int 和 枚举名以外的信息时,可以使用 DescriptionAttribute 属性,设置描述信息然后读取
/// <summary>
/// 获取枚举的描述
/// </summary>
/// <param name="enum">枚举值</param>
/// <returns>description</returns>
public static string ToDescription(this Enum @enum)
{
MemberInfo[] member = @enum.GetType().GetMember(@enum.ToString());
if (member.Length != 0)
{
string description = GetDescription(member[0]);
if (description != null)
{
return description;
}
}
return @enum.ToString();
}
/// <summary>
/// 获取成员信息的 Description
/// </summary>
/// <param name="memberInfo">成员信息</param>
/// <returns>Description</returns>
private static string GetDescription(MemberInfo memberInfo)
{
var type = typeof(DescriptionAttribute);
var attribute = memberInfo.GetCustomAttribute(type) as DescriptionAttribute;
return attribute?.Description;
}
var red = Color.Red.ToDescription();//红色
var green = Color.Green.ToDescription();//绿色
var blue = Color.Blue.ToDescription();//蓝色
枚举的扩展方法
示例代码:https://gitee.com/sayook/Extensions/blob/master/Extensions/EnumExtensions.cs