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()))
                {

                }
            }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM