加载中…
个人资料
李大伟_大不发音
李大伟_大不发音
  • 博客等级:
  • 博客积分:0
  • 博客访问:1,124
  • 关注人气:4
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

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

(2011-12-30 15:55:45)
标签:

杂谈

分类: 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);
            }



0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有