C#中实现对象间的更新操作

时间:2022-04-23 06:59:22

最近工作的时候遇到一个问题,根据Web端接收到的对象obj1,更新对应的对象值ogj2。先判断obj1中属性值是否为null,

若不等于null,则更新obj2中对应属性值;若等于null,则保持obj2中对应属性值不变。

先创建Student Class:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Property
{
public class Student
{
public string Name { get; set; } public string number { get; set; } public string School {get;set;} public string Score { get; set; }
}
}

方法实现:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Property
{
class Program
{
static void Main(string[] args)
{
Student std1 = new Student();
std1.Name = "Zhang San";
std1.number = "";
std1.School = "Jiangnan University";
std1.Score = "87.98"; Student std2 = new Student();
std2.Name = "Li Si";
std2.Score = "98.98"; Console.WriteLine("Before:");
foreach (System.Reflection.PropertyInfo p in std1.GetType().GetProperties())
{
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(std1,null)); } foreach (System.Reflection.PropertyInfo p in std2.GetType().GetProperties())
{
//Console.WriteLine("{0}: {1}", p.Name, p.GetValue(std2, null));
if (p.GetValue(std2, null) != null)
p.SetValue(std1, p.GetValue(std2, null), null);
}
Console.WriteLine("After:");
foreach (System.Reflection.PropertyInfo p in std1.GetType().GetProperties())
{
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(std1, null)); }
Console.ReadKey(); }
}
}

结果:

  C#中实现对象间的更新操作

2016-04-30