C#获取dynamic(动态)实体的属性值

当我们遍历一个已知实体类时我们可以这样来做,但是动态实体无法获取到类的GetType()

    List<student> item= conn.Query<student>($"select * from 表  where id=123 ").ToList();
    foreach (System.Reflection.PropertyInfo p in item.GetType().GetProperties())
                {
                    Console.WriteLine(p.Name+ " :"+p.GetValue(item, null));
                }
     
    class student{
    public string id{get;set;}
    public string name{get;set;}
    public string sex{get;set;}
    }

当我们需要遍历动态一个实体想要知道某个字段有没有值时,我们可以这样来写

            List<dynamic> result = conn.Query($"select * from 表 where id='123'").ToList();
            foreach (KeyValuePair<string, object> col in result[0])
            {
                string aa = col.Key;//属性
                string bb = col.Value.ToString();//
                if (!string.IsNullOrWhiteSpace(col.Value.ToString()))
                {

                }
            }

 

posted @ 2020-12-13 15:56  恋上微笑的天使  阅读(6350)  评论(0编辑  收藏  举报