主要是使用递归循环出,类的所有属性,其中需要判断属性的类型是否泛型或是否基本类型,尤其注意string类型;如果是字段类型的DateTime或者?类型 请记得调整反射代码。
class Program
{
static Type parent = null;
static List<string> listProperty = new List<string>();
static void Main(string[] args)
{
GetMemberInfoName(typeof(BigHouse).GetProperties());
}
public static List<string> GetMemberInfoName(PropertyInfo[] properties)
{
string Name = string.Empty;
foreach (PropertyInfo propertie in properties)
{
if (propertie.PropertyType.IsGenericType
&&
propertie.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
parent = propertie.PropertyType.GetGenericArguments().First<Type>();
GetMemberInfoName(parent.GetProperties());
}
else if (propertie.PropertyType.IsPrimitive == false
&& propertie.PropertyType.Name != "String")
{
parent = propertie.PropertyType;
GetMemberInfoName(propertie.PropertyType.GetProperties());
}
else if (propertie.PropertyType.IsPrimitive == true
|| propertie.PropertyType.Name == "String")
{
if (parent != null)
Name = parent.Name + "." + propertie.Name;
else
Name = propertie.Name;
listProperty.Add(Name);
}
}
return listProperty;
}
}
类的模型定义:
public class BigHouse
{
/// <summary>
/// 户主姓名
/ </summary>
public string Name { get; set; }
/// <summary>
/// 所属行政区域
/// </summary>
public string Area { get; set; }
public Address address { get; set; }
public List<Family> Listfamily { get; set; }
}
public class Address
{
public string addr { get; set; }
public string Telephone { get; set; }
}
public class Family
{
public string Name { get; set; }
public string Sex { get; set; }
}