c# 类重写Equal,GetHashCode,实现IComparable,IComparable<T>
/// <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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!