<?xml version="1.0" encoding="UTF-8"?>
以下方法实现了遍历一个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
);
}
}
}
}
转载于:https://blog.51cto.com/muzizongheng/1333075