既然要比较我们先建个实体
public class Student
{
/// <summary>
/// 学号
/// </summary>
[Description("学号")]
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
[Description("姓名")]
public string Name { get; set; }
}
实体建好了我们赋值吧
Student model = new Student();
model.Id = 1;
model.Name = "测试1";
list.Add(model);
Student model1 = new Student();
model1.Id = 1;
model1.Name = "测试2";
我们发现如果是记日志的话我们希望记 {0}值变更:{1}=>{2};\n
那我们怎么弄呢
我们应该先获取所传入的类是否相同
var A = model.GetType();
var B = model1.GetType();
if (A.ToString()!=B.ToString())
{
Console.WriteLine("传入实体不同");
Console.ReadKey();
}
我们还要比较类中有哪些属性
那我们就要用到一个方法GetProperties();
var A1 = model.GetType().GetProperties();

这样我们就拿到了一个类的所有属性
那我们要遍历每个属性在两个实体是否相等了
for (int i = 0; i < A1.Length; i++)
{
}
下面是怎么获取每个属性的对应值呢
那么我们就要用GetValue() 了
var bef = A1[i].GetValue(model) == null ? string.Empty : A1[i].GetValue(model);
var aft = A1[i].GetValue(model1) == null ? string.Empty : A1[i].GetValue(model1);
那么我们只要比较一下就行了
if (!bef.Equals(aft))
{
//获取实体定义的属性[Description("姓名")]、[Description("学号")]
var desObject = (DescriptionAttribute)Attribute.GetCustomAttribute(A1[i], typeof(DescriptionAttribute));
string des = string.Empty;
if (desObject != null)
{
des = desObject.Description;
}
str += des + A1[i].Name + string.Format("值变更:{0}=》{1};\n", bef, aft);
}
那样我们的方法就写完了
下面是完整的代码
public static string CompareObjectDif(object bef ,object aft)
{
string str = String.Empty;
var A = bef.GetType();//获取类
var B = aft.GetType();
if (A.ToString() != B.ToString())
{
str = "实体不同";
return str;
}
var A1 = bef.GetType().GetProperties();//获取类所有公共属性
for (int i = 0; i < A1.Length; i++)
{
var befModel = A1[i].GetValue(bef) == null ? string.Empty : A1[i].GetValue(bef);//获取所有属性值
var aftModel = A1[i].GetValue(aft) == null ? string.Empty : A1[i].GetValue(aft);
if (!befModel.Equals(aftModel))
{
var desObject = (DescriptionAttribute)Attribute.GetCustomAttribute(A1[i], typeof(DescriptionAttribute));
string des = string.Empty;
if (desObject != null)
{
des = desObject.Description;
}
str += des + A1[i].Name + string.Format("值变更:{0}=》{1};\n", befModel, aftModel);
}
}
return str;
}
下面是主方法
static void Main(string[] args)
{
List<Student> list = new List<Student>();
Student model = new Student();
model.Id = 1;
model.Name = "测试1";
list.Add(model);
Student model1 = new Student();
model1.Id = 1;
model1.Name = "测试2";
var str = CompareObjectDif(model, model1);
Console.WriteLine(str);
Console.ReadKey();
}
好了写完
浙公网安备 33010602011771号