/// <summary> /// 获取某个类型声明的信息 /// </summary> /// <param name="classType"></param> /// <returns></returns> public IList <DescriptionItemValue> GetDescriptionItems(Type classType) { var list = new List <DescriptionItemValue>(); if (classType.IsEnum) { var names = Enum.GetNames(classType); foreach (var name in names) { var filedInfo = classType.GetField(name); var attributes = filedInfo.GetCustomAttributes(typeof(DescriptionItemAttribute), false); if (attributes.Length > 0) { var att = (DescriptionItemAttribute)attributes[0]; var enumFiledValue = new DescriptionItemValue { Description = att.Description }; enumFiledValue.FieldName = !string.IsNullOrEmpty(att.Name) ? att.Name : name; enumFiledValue.FieldValue = name; list.Add(enumFiledValue); } } } else { var memberInfos = classType.GetMembers(BindingFlags.Static | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic); foreach (var memberInfo in memberInfos) { var customAttributes = memberInfo.GetCustomAttributes(typeof(DescriptionItemAttribute), false); if (customAttributes.Length > 0) { var att = (DescriptionItemAttribute)customAttributes[0]; if (memberInfo is FieldInfo fieldInfo) { var fieldValue = SimpleConstFieldValue(classType, att, fieldInfo); list.Add(fieldValue); } else if (memberInfo is PropertyInfo propInfo) { var fieldValue = SimpleConstFieldValue(classType, att, propInfo); list.Add(fieldValue); } } } } return(list); }
private static DescriptionItemValue SimpleConstFieldValue(Type classType, DescriptionItemAttribute att, FieldInfo propInfo) { var fieldValue = new DescriptionItemValue { Description = att.Description, FromType = classType }; fieldValue.FieldName = !string.IsNullOrEmpty(att.Name) ? att.Name : propInfo.Name; if (propInfo.IsStatic) { fieldValue.FieldValue = propInfo.GetValue(null).ToString(); } else { var instance = Activator.CreateInstance(classType); fieldValue.FieldValue = propInfo.GetValue(instance).ToString(); } return(fieldValue); }