C#枚举高级应用

我们经常使用枚举,但是可能只是一些简单的应用,其实在我们的项目中用到的 下拉列表、Model属性类型等,都可以利用枚举更好的实现。

//定义枚举

public enum DepartmentEum    {        [Description("第一产品事业部")]        FirstDept = 1

}

1、下拉列表使用枚举数据源:

 //绑定部门
    var deptList = EnumHelper.GetCachedDictionary(typeof(DepartmentEum ));
    var ddlDeptList = new List<SelectListItem>();
    ddlDeptList.Add(new SelectListItem() { Text = "请选择", Value = "-1" });
    foreach (var item in deptList)
    {
        ddlDeptList.Add(new SelectListItem() { Text = item.Value, Value = item.Key });
    }

 

2、Model属性类型:

        /// <summary>
        /// 部门枚举
        /// </summary>
        [DataMember]
        public DepartmentEum Department { get; set; }

        //获取枚举值

        (int)model.Department

        //获取枚举描述信息

         EnumHelper.GetEnumDescription(model.Department)

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

3、以下是枚举帮助类

EnumHelper.cs
public static class EnumHelper
 {
  private static readonly Hashtable ht = Hashtable.Synchronized(new Hashtable());  /// <summary>
  /// 从缓存中获取枚举对应的List
  /// </summary>
  /// <param name="type"></param>
  /// <returns></returns>
  public static IList<KeyValuePair<string, string>> GetCachedDictionary(Type type)
  {
   if (ht.Contains(type))
   {
    return ht[type] as IList<KeyValuePair<string, string>>;
   }
   else
   {
    IList<KeyValuePair<string, string>> dict = GetDictionary(type);
    ht[type] = dict;
    return dict;
   }
  }  public static IList<KeyValuePair<string, string>> GetDictionary(Type type)
  {
            if (!type.IsEnum) 
            {
                throw new InvalidOperationException("错误的枚举类型");
            }
   FieldInfo[] fields = type.GetFields();
   IList<KeyValuePair<string, string>> dict = new List<KeyValuePair<string, string>>();
            foreach (var item in fields)
            {
                if (item.FieldType.IsEnum == false) { continue; }
    string desription = string.Empty;
    object[] objs = item.GetCustomAttributes(typeof (DescriptionAttribute), false);
    if (objs != null && objs.Length> 0)
    {
     DescriptionAttribute da = (DescriptionAttribute) objs[0];
     desription = da.Description;
    }
    else
    {
     desription = item.Name;
    }
    dict.Add(new KeyValuePair<string, string>(((int) Enum.Parse(type, item.Name)).ToString(), desription));
   }
   return dict;
  }  public static string GetCachedDescription(Type type, string fieldName)
  {
   IList<KeyValuePair<string, string>> dictionary = GetCachedDictionary(type);
   foreach (KeyValuePair<string, string> keyValuePair in dictionary)
   {
    if (keyValuePair.Key == ((int) (Enum.Parse(type, fieldName))).ToString())
    {
     return keyValuePair.Value;
    }
   }
   return fieldName;
  }  public static string GetCachedFieldName(Type type, string description)
  {
   IList<KeyValuePair<string, string>> dictionary = GetCachedDictionary(type);
   foreach (KeyValuePair<string, string> keyValuePair in dictionary)
   {
    if(keyValuePair.Value == description)
    {
     return keyValuePair.Key;
    }
   }
   return description;
  }        ///<summary>
        /// 根据枚举类型获取描述
        ///</summary>
        ///<param name="enumSubitem">类型</param>
        ///<returns>描述</returns>
        public static string GetEnumDescription(Enum value)
        {
            // Get the Description attribute value for the enum value
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return value.ToString();
            }
        }        /// <summary>
        /// 从缓存中获取枚举对应的List[添加一空白列]
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IList<KeyValuePair<string, string>> GetCachedDictionaryBlank(Type type)
        {
            if (ht.Contains(type))
            {
                return ht[type] as IList<KeyValuePair<string, string>>;
            }
            IList<KeyValuePair<string, string>> dict = GetDictionary(type);
            dict.Insert(0, new KeyValuePair<string, string>((-1).ToString(), string.Empty));
            ht[type] = dict;
            return dict;
        }        public static KeyValuePair<string, string> GetEnum(Type type, string fieldName)
        {
            KeyValuePair<string, string> kvp = new KeyValuePair<string, string>();
            IList<KeyValuePair<string, string>> dictionary = GetCachedDictionary(type);
            foreach (KeyValuePair<string, string> keyValuePair in dictionary)
            {
                if (keyValuePair.Key == ((int)(Enum.Parse(type, fieldName))).ToString())
                {
                    kvp = keyValuePair;
                    break;
                }
            }
            return kvp;
        }
 }
 

 

 

 
 


 

阅读更多
个人分类: .net C#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭