比较同一个类的实例并使用新值

时间:2016-09-02 11:00:26

标签: c# compare comparison updatemodel

比较同一个班级的实例。

public class Student()
{
    public string Name {get; set;}
    public string Hobby {get; set;}
    public string Country {get; set;}
}

Student old = new Student { Name = "A", Hobby = "Swim", Country = "HK" };
Student new = new Student { Name = "A", Hobby = "Jog", Country = "US" };

比较new和new是否相等,否则,替换不同类的每个字段。比如将旧值更新为新值。

If(old != new)
{
    UpdateOldWithNew(old, new);
}

1 个答案:

答案 0 :(得分:0)

    Student student1 = new Student { Name = "A", Hobby = "Swim", Country = "HK" };
    Student student2 = new Student { Name = "A", Hobby = "Jog", Country = "US" };   
    Student student3 = new Student { Name = "A", Hobby = "Swim", Country = "HK" };

    //reference equal 
    System.Debug.WriteLine(student1 == student2); //false
    System.Debug.WriteLine(student1 == student3); //false
    System.Debug.WriteLine(student1 == student1); //true


    if(student1 != student2)
    {
        student1 = student2;
    }