循环遍历对象属性进行赋值取值,同类不同对象属性值比较,属性值复制叠加

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);

 输出结果:

 

posted on 2021-10-19 16:41  写abcd的猴子  阅读(906)  评论(0编辑  收藏  举报