zoukankan      html  css  js  c++  java
  • [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);
              }
  • 相关阅读:
    2017 《Java》预备作业计科1502宋奇蕊
    在 Kubernetes 上调度 GPU 资源
    ceph
    网络设备的 38 个知识点
    CF1066 ABCD
    单调队列优化动态规划
    对拍
    【关于此博客】
    使用Morphia框架操作mongodb
    通过mybatis读取数据库数据并提供rest接口访问
  • 原文地址:https://www.cnblogs.com/shadowwalker/p/2833457.html
Copyright © 2011-2022 走看看