/// <summary> /// 获取枚举成员描述信息及名称 /// 返回:IDictionary /// Value:描述信息 /// Key:值 /// </summary> /// <typeparam name="T">struct类型</typeparam> /// <returns>IDictionary</returns> protected IDictionary<string, string> GetEnumMemberList<T>() where T : struct { var members = typeof(T).GetMembers().Where(s => s.MemberType == System.Reflection.MemberTypes.Field); Dictionary<string, string> dict = new Dictionary<string, string>(); foreach (var member in members) { var attrs = member.GetCustomAttributes(typeof(DescriptionAttribute), false); if (!attrs.Any()) { continue; } var memberinfo = attrs[0] as DescriptionAttribute; if (memberinfo != null) { dict.Add(member.Name, memberinfo.Description); } } return dict; } /// <summary> /// 调用方法 /// </summary> /// <param name="selectId"></param> /// <returns></returns> protected List<SelectListItem> Execute(int selectId) { var dict = GetEnumMemberList<SharedScope>(); var list = new List<SelectListItem>(); foreach (var info in dict) { int value = (int)Enum.Parse(typeof(SharedScope), info.Key); list.Add( new SelectListItem { Value = value.ToString(), Text = info.Value, Selected = value == selectId }); } this.ViewData["Execute"] = list; return list; }
上面代码是一个泛型的操作枚举的C#语言实现的工具类方法。