C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值,以及该类的实例的使用集合数组的属性名称、 值,并按照属性名称进行排序,如果该字段为空和空字符串不输出该项。
实体类
public partial class SysUser { public string Id { get; set; } public string Name { get; set; } public List<SysRole> SysRole { get; set; } public SysOrgCategory[] SysOrgCategory { get; set; } } public partial class SysRole { public string RoleId { get; set; } public string RoleName { get; set; } } public partial class SysOrgCategory { public string OrgId { get; set; } public string OrgName { get; set; } }
反射获取属性名称、 值,以及该类的实例的使用集合数组的属性名称、 值,并按照属性名称进行排序,如果该字段为空和空字符串不输出该项。
public static string GetProperties<T>(T t) { Type type = t.GetType(); StringBuilder sb = new StringBuilder(); foreach (PropertyInfo property in type.GetProperties().OrderBy(p=> p.Name)) { object o = property.GetValue(t, null); if (o == null) { continue; } else { if (string.IsNullOrWhiteSpace(o.ToString())) { continue; } } sb.Append(property.Name + "="); if (property.PropertyType.IsGenericType) { var listVal = property.GetValue(t, null) as IEnumerable<object>; if (listVal == null) continue; foreach (var item in listVal) { sb.Append(GetProperties(item)); } } else if (property.PropertyType.IsArray) { var listVal = property.GetValue(t, null) as IEnumerable<object>; foreach (var item in listVal) { sb.Append(GetProperties(item)); } } else { sb.Append(property.GetValue(t, null)); sb.Append("&"); } } return sb.ToString().Trim('&'); }
测试代码:
SysUser sysUser = new SysUser(); sysUser.Id= "1332"; sysUser.Name = null; List<SysRole> Role = new List<SysRole>(); Role.Add(new SysRole() { RoleId = "1", RoleName = "aa" }); Role.Add(new SysRole() { RoleId = "2", RoleName = "bb" }); SysOrgCategory[] Org = new SysOrgCategory[2] { new SysOrgCategory() { OrgId = "1" }, new SysOrgCategory() { OrgId = "2" } }; sysUser.SysOrgCategory = Org; sysUser.SysRole = Role; Console.WriteLine(GetProperties(sysUser)); Console.Read();
效果
根据需要进行修改值进行展示。