以下方法实现了遍历一个class中所有的字段, 并且递归遍历sub class。
private StringBuilder _properties = new StringBuilder();
public MainView()
{
TraversalProperties(typeof(StudyInfoModel));
File.WriteAllText("Properties.txt", _properties.ToString());
}
private void TraversalProperties(Type classTemplate)
{
if (null == classTemplate)
{
return;
}
foreach (PropertyInfo pi in
classTemplate.GetProperties(BindingFlags.Public | BindingFlags.Instance| BindingFlags.DeclaredOnly))
{
PropertyInfo needUpdateValue = classTemplate.GetProperty(pi.Name);
if (needUpdateValue.PropertyType.Equals(classTemplate))
{
return;
}
if (needUpdateValue.PropertyType.IsArray
|| (needUpdateValue.PropertyType.IsClass
&& !needUpdateValue.PropertyType.IsGenericType
&& !needUpdateValue.PropertyType.Equals(typeof(String))
&& !needUpdateValue.PropertyType.IsValueType
)
)
{
TraversalProperties(needUpdateValue.PropertyType);
}
else if (needUpdateValue.PropertyType.IsGenericType
&& needUpdateValue.PropertyType.GetGenericTypeDefinition()== typeof(ObservableCollection<>))
{
TraversalProperties(needUpdateValue.PropertyType.GetGenericArguments()[0]);
}
else
{
if (classTemplate.Name.Contains("StudyInfoModel"))
{
_properties.AppendFormat(""{0}", ", needUpdateValue.Name);
}
else
{
_properties.AppendFormat(""{0}_{1}", ", classTemplate.Name.Replace("InfoModel", ""), needUpdateValue.Name);
}
}
}
}