循環遍歷對象屬性進行賦值取值,同類不同對象屬性值比較,屬性值復制疊加


1.創建用於測試驗證的實體類

class Model {
        public string Test1 { get; set; }
        public string Test2 { get; set; }
        public string Test3 { get; set; }
    }

2.創建該類的兩個對象,用於后面進行比較、屬性復制

Model model = new Model(); 

Model model2 = new Model() {Test1 = "test" };

3.給model對象的屬性賦值,這里我們采用非常規方法,通過遍歷屬性值,來賦值 

 PropertyInfo[] propertys = model.GetType().GetProperties(); //獲取model的所有公共屬性
            int index = 0;
            foreach (PropertyInfo info in propertys) {//遍歷屬性,給對象屬性賦值
                info.SetValue(model,"test" + index);
                index++;
            }

4.打印輸出model對象,遍歷獲取對象屬性,驗證屬性賦值是否成功

PrintValue(model,label1);

 private void PrintValue(Model model, Label label) {
            PropertyInfo[] propertys = model.GetType().GetProperties();
            foreach (PropertyInfo info in propertys)
            {
                string name = info.Name;
                string value = info.GetValue(model).ToString();
                label.Content += name + ":" + value + "\n"; 
            }
        }

 

輸出結果:

5.通過比較model2與model屬性值的差異,將model屬性疊加復制給model2

PropertyInfo[] propertys = model.GetType().GetProperties();
            foreach (PropertyInfo info in propertys) {
                if (info.GetValue(model2) == null)
                {
                    info.SetValue(model2, info.GetValue(model).ToString());
                }
                else {
                    info.SetValue(model2, info.GetValue(model2).ToString() + "," + info.GetValue(model).ToString());
                }
            }

6.打印model2,輸出結果驗證  

PrintValue(model2,label2);

輸出結果:

 

 7.將model2轉換為json字符串

string str = JsonConvert.SerializeObject(model2);

 輸出結果:

 


免責聲明!

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



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