枚举初使用
1,定义一个枚举:
public enum MatRequireStatus { /// <summary> /// 待处理 /// </summary> [Description("待处理")] Pending = 0, /// <summary> /// 已派单 /// </summary> [Description("已派单")] HasBeenSent = 1, /// <summary> /// 已处理 /// </summary> [Description("已处理")] Processed = 2 }
2,使用枚举赋值。
TransOrder transOrder = new TransOrder() { Status = Convert.ToDouble( MatRequireStatus.Pending) };
3,获取枚举的名称:
foreach (var item in list) { item.StatusDesc = Enum.GetName(typeof(MatRequireStatus), Convert.ToInt32(item.Status)); }
4,获取枚举的描述:
4.1新增方法:
/// <summary> /// 获取枚举值的描述文本 /// </summary> /// <param name="e">枚举值</param> /// <returns></returns> public string Description(Enum e) { Type enumType = e.GetType(); var fieldInfo = enumType.GetFields().FirstOrDefault(a => a.Name == Enum.GetName(enumType, e)); object[] obj = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (obj == null) return null; DescriptionAttribute des = (DescriptionAttribute)obj[0]; return des.Description; }
4.2调用方法获取枚举描述:
MatRequireStatus mat = MatRequireStatus.Processed; var desc= Description(mat);
或者
foreach (var item in list)
{
item.StatusDesc = Description((MatRequireStatus)Convert.ToInt32(item.Status));
}
5,将枚举转换为列表
代码有点长,有需要的话,我再发。