[C#] 遍历对象属性、遍历结构体字段

[C#] 遍历对象属性、遍历结构体字段

 
最近需要将原有的SQL数据库中的数据导入到MongoDB中
 
同事提供了对象的结构体,该结构体中包含嵌套的结构体
 
我需要得到结构中的每个字段的值
 
没其他方法 ,遍历吧 同学
 
1.遍历结构体:
 
其中 ResumeInfo为结构体[并且内嵌了结构体]
 
ResumeInfo resume1 = new ResumeInfo();
FieldInfo[] fieldInfos = typeof(ResumeInfo).GetFields();
int FieldCount = fieldInfos.Length;
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);
} }
 
1.遍历类:
 
其中 Resume为一个类
 
PropertyInfo[] properties = typeof(Resume).GetProperties();
          foreach (PropertyInfo p in properties)
          {
              NewResume[p.Name] = p.GetValue(ResumeInfo, null);
          }

posted on 2012-12-26 09:58  fqzhang  阅读(2738)  评论(0编辑  收藏  举报

导航