C# 在以下情况下,寻找使变量相等的解决方案

C# 在以下情况下,寻找使变量相等的解决方案,c#,C#,问题是,如果s1等于s2,则答案将为false,但使s1等于s2的方法是什么?您必须重写Equals和GetHashCode,否则只比较引用: var s1=new Student{ id=1,name="Sachin" } var s2=new Student{ id=1,name="Sachin" } 在本例中,只有当id和名称都相等时,两个学生才相等。相应地改变它 实际上没有必要重载EqualsStudent并重写GetHashCode。但我们强烈建议这样做。阅读:假设您的ID字段在所有

问题是,如果s1等于s2,则答案将为false,但使s1等于s2的方法是什么?

您必须重写Equals和GetHashCode,否则只比较引用:

var s1=new Student{ id=1,name="Sachin" }
var s2=new Student{ id=1,name="Sachin" }
在本例中,只有当id和名称都相等时,两个学生才相等。相应地改变它


实际上没有必要重载EqualsStudent并重写GetHashCode。但我们强烈建议这样做。阅读:

假设您的ID字段在所有用户之间是唯一的,为什么不使用它作为您的平等性检查

public class Student
{
    public int Id { get;  set; }
    public string Name { get;set; }

    public override bool Equals(object obj)
    {
        Student s2 = obj as Student;
        if (s2 == null) return false;
        return this.Equals(s2);
    }

    public bool Equals(Student s)
    {
        if (s == null) return false;
        return Id == s.Id && Name == s.Name;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + Id;
            hash = hash * 23 + Name.GetHashCode();
            return hash;
        }
    }
}
通常最好先从最简单的解决方案开始,然后再深入研究更多,你可能会发现这就是你所需要的

if (s1.id == s2.id) {
   ...
}