[C#] 遍历对象属性、遍历结构体字段
(2011-12-30 15:55:45)
标签:
杂谈 |
分类: C# |
最近需要将原有的SQL数据库中的数据导入到MongoDB中
for (int i = 0; i
< FieldCount; i++)
{
FieldInfo
FiledFirstLayer = fieldInfos[i];
object Value =
FiledFirstLayer.GetValue(resume1);
if (Value != null
&& Value.ToString() !=
"0")
{
//新建子节点文档
Document ChildDoc = new
Document();
FieldInfo[]
tmpFieldInfos = FiledFirstLayer.GetValue(resume1).GetType().GetFields();
int
tmpFiledCount =
tmpFieldInfos.Length;
for (int j = 0; j
< tmpFiledCount; j++)
{
ChildDoc[tmpFieldInfos[j].Name] = new
Document() .Add("label", null) .Add("value", null) .Add("type",
null) .Add("model", null); } Resume[FiledFirstLayer.Name] =
ChildDoc;
}
else
{
Resume[FiledFirstLayer.Name] = new
Document() .Add("label", null) .Add("value", null) .Add("type",
null) .Add("model", null);
} }
foreach (PropertyInfo p in
properties)
{
NewResume[p.Name] = p.GetValue(ResumeInfo, null);
}
同事提供了对象的结构体,该结构体中包含嵌套的结构体
我需要得到结构中的每个字段的值
没其他方法 ,遍历吧 同学
1.遍历结构体:
其中 ResumeInfo 为结构体[并且内嵌了结构体]
ResumeInfo
resume1 = new ResumeInfo();
FieldInfo[] fieldInfos =
typeof(ResumeInfo).GetFields();
int FieldCount =
fieldInfos.Length;
1.遍历类:
其中 Resume 为一个类对象
PropertyInfo[] properties = typeof(Resume).GetProperties();