using System.Reflection; namespace YLErp.Web.Areas.Admin.Models { /// /// /// public class OtcFormatViewModel { public IEnumerable SelectItems { get; set; } public static OtcFormatViewModel CreateViewModel(OtcFormatModel otcFormat) { if (otcFormat is null) { throw new System.ArgumentNullException(nameof(otcFormat)); } var selectItems = GetSelectItems(otcFormat); return new OtcFormatViewModel { SelectItems = selectItems }; } private static IEnumerable GetSelectItems(object obj, int depth = 0) { var flags = BindingFlags.Instance | BindingFlags.Public; var properties = obj.GetType().GetProperties(flags); var resultList = new List(properties.Length); foreach (var p in properties) { if (p.CanRead && p.CanWrite) { var attr = p.GetCustomAttribute(typeof(OtcFormatConfigAttribute)) as OtcFormatConfigAttribute; if (attr == null) { continue; } var item = new SelectItemNest { Value = p.Name, Text = attr.Label, Tag = p.GetValue(obj) }; if (depth == 0) { item.SelectItems = GetSelectItems(item.Tag, depth + 1); } resultList.Add(item); } } return resultList; } } }