# Extensions **Repository Path**: sayook/Extensions ## Basic Information - **Project Name**: Extensions - **Description**: 扩展工具 - **Primary Language**: C# - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2020-05-19 - **Last Updated**: 2022-09-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 枚举的扩展 示例枚举: ```c# public enum Color { [Description("红色")] Red, [Description("绿色")] Green = 7, [Description("蓝色")] Blue } ``` ##### Enum转Int ```c# int red = (int)Color.Red;//0 int green = (int)Color.Green;//7 int blue = (int)Color.Blue;//8 ``` * 枚举类型默认为**Int** * 枚举值默认从0开始,并依次递增 ##### Int转Enum ```c# Color a = (Color)5;//不报错 Color b = (Color)7; Console.WriteLine(a.ToString());//5 Console.WriteLine(b.ToString());//Green ``` * **Int** 可以直接转 **Enum** * 枚举可能会得到非预期的值(值没有对应的成员),不会报错 ##### Enum转String ```c# var red = Color.Red.ToString();//Red var green = Color.Green.ToString();//Green var blue = Color.Blue.ToString();//Blue ``` ##### String转Enum ```c# var green = Enum.Parse(typeof(Color), "Green");//Color.Green var black = Enum.Parse(typeof(Color), "Black");//throw ArgumentException Enum.TryParse("Black", out var blackTry);//Color.Red ``` * 和枚举名相同的字符可以转成相对应的枚举(区分大小写) * 转化不存在的字符,会抛出异常(不同于Int) * 使用Enum.TryParse转换,不存在,则返回默认枚举 * ***枚举的默认值 0,即使没有为0的成员*** ##### 读取Description 当我需要展示枚举 Int 和 枚举名以外的信息时,可以使用 **DescriptionAttribute** 属性,设置描述信息然后读取 ```c# /// /// 获取枚举的描述 /// /// 枚举值 /// description 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(); } /// /// 获取成员信息的 Description /// /// 成员信息 /// Description private static string GetDescription(MemberInfo memberInfo) { var type = typeof(DescriptionAttribute); var attribute = memberInfo.GetCustomAttribute(type) as DescriptionAttribute; return attribute?.Description; } ``` ```c# 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 相关好文:https://mp.weixin.qq.com/s/f9Wc3kIKF4K1zHkHuHyp3w