HashCode 的作用及其在 .NET 中的应用
在 .NET 中,IEqualityComparercsharppublic class StudentNameComparer : IEqualityComparer<Student>{ public bool Equals(Student x, Student y) { if (x == null && y == null) return true; else if (x == null || y == null) return false; return x.Name == y.Name; } public int GetHashCode(Student obj) { if (obj == null) return 0; return obj.Name.GetHashCode(); }}接下来,我们使用 StudentNameComparer 来创建一个哈希集合,并将几个学生对象添加到其中。代码如下:csharpvar comparer = new StudentNameComparer();var students = new HashSet<Student>(comparer);students.Add(new Student { Name = "Alice", Age = 20 });students.Add(new Student { Name = "Bob", Age = 21 });students.Add(new Student { Name = "Alice", Age = 22 });在上述代码中,我们使用了自定义的比较器 StudentNameComparer,并将其传递给 HashSetCopyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号