c# 类重写Equal,GetHashCode,实现IComparable,IComparable<T>

发布时间 2024-01-06 20:44:36作者: 孙延坤

/// <summary>
/// Array,List<T> 排序都依赖于IComparable
/// </summary>
public class Student : IEquatable<Student>,IComparable, IComparable<Student>
{
public int Id { get; set; }
public string Name { get; set; }

public Student()
{
}

public Student(int id, string name) : this()
{
this.Id = id;
this.Name = name;
}

/// <summary>
/// 实现IEquatable<T>接口的Equals
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Student other)
{
if (other is null)
return false;

return this.Id == other.Id && this.Name == other.Name;
}

/// <summary>
/// 重写Object基类的Equals
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
var other = obj as Student;
return this.Equals(other);
}

/// <summary>
/// 重写Object基类的GetHashCode
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return Tuple.Create(this.Id, this.Name).GetHashCode();
}

public int CompareTo(Student other)
{
return this.Id - (other is null ? 0 : other.Id);
}

public int CompareTo(object obj)
{
return CompareTo(obj as Student);
}

/// <summary>
/// 重载==运算符
/// </summary>
/// <param name="ls"></param>
/// <param name="rs"></param>
/// <returns></returns>
public static bool operator ==(Student ls, Student rs)
{
return (ls is null && rs is null) || ls is not null && ls.Equals(rs) || rs is not null && rs.Equals(ls);
}

/// <summary>
/// 重载!=运算符
/// </summary>
/// <param name="ls"></param>
/// <param name="rs"></param>
/// <returns></returns>
public static bool operator !=(Student ls, Student rs)
{
return !(ls == rs);
}
}