在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
考虑到identity属性可以为null,以下哪项是正确/更好的.
public override int GetHashCode()
{
if (ID == null) {
return base.GetHashCode();
}
return ID.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
要么
public override int GetHashCode()
{
if (ID != null) {
return ID.GetHashCode();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
更新1:更新了第二个选项.
更新2:以下是Equals实现:
public bool Equals(IContract other)
{
if (other == null)
return false;
if (this.ID.Equals(other.ID)) {
return true;
}
return false;
}
public override bool Equals(object obj)
{
if (obj == null)
return base.Equals(obj);
if (!obj is IContract) {
throw new InvalidCastException("The 'obj' argument is not …Run Code Online (Sandbox Code Playgroud) 我如何处理GetHashCode函数中的空字段?
Module Module1
Sub Main()
Dim c As New Contact
Dim hash = c.GetHashCode
End Sub
Public Class Contact : Implements IEquatable(Of Contact)
Public Name As String
Public Address As String
Public Overloads Function Equals(ByVal other As Contact) As Boolean _
Implements System.IEquatable(Of Contact).Equals
Return Name = other.Name AndAlso Address = other.Address
End Function
Public Overrides Function Equals(ByVal obj As Object) As Boolean
If ReferenceEquals(Me, obj) Then Return True
If TypeOf obj Is Contact Then
Return Equals(DirectCast(obj, Contact)) …Run Code Online (Sandbox Code Playgroud) 实现IEqualityComparer<Product>(Product是一个类)时,ReSharper会抱怨下面的空检查始终为false:
public int GetHashCode(Product product)
{
// Check whether the object is null.
if (Object.ReferenceEquals(product, null))
return 0;
// ... other stuff ...
}
Run Code Online (Sandbox Code Playgroud)
(来自Enumerable.Except的MSDN VS.9文档的代码示例)
ReSharper可能是错的,但在搜索答案时,我遇到了官方文档,IEqualityComparer<T>其中有一个示例,其中未检查null:
public int GetHashCode(Box bx)
{
int hCode = bx.Height ^ bx.Length ^ bx.Width;
return hCode.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
此外,该文档GetHashCode()的状态的是ArgumentNullException将被抛出时"类型obj的是引用类型和obj为null".
因此,在实现时IEqualityComparer应该GetHashCode检查null,如果是,那么它应该用null做什么(抛出异常或返回一个值)?
我最感兴趣的是.NET框架官方文档,如果应该检查null,则指定这种或那种方式.
我有这个类,在那里我覆盖了 Object Equals:
public class Foo
{
public string string1 { get; set; }
public string string2 { get; set; }
public string string3 { get; set; }
public override bool Equals(object other)
{
if (!(other is Foo)) return false;
Foo otherFoo = (other as Foo);
return otherFoo.string1 == string1 && otherFoo.string2 == string2 && otherFoo.string3 == string3;
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一个警告“覆盖 object.equals 但不覆盖 object.gethashcode”,我理解覆盖 GetHashCode 的必要性,以便我的类型根据可散列类型进行操作。
据我研究,为了使此代码唯一,通常使用 XOR 运算符,或者涉及素数乘法。所以,根据我的消息来源,来源1和源2我正在考虑我的GesHashCode覆盖方法这两个选项。
1:
public override int GetHashCode() {
return …Run Code Online (Sandbox Code Playgroud) gethashcode ×4
c# ×3
equality ×2
iequatable ×2
.net ×1
algorithm ×1
hash ×1
hashcode ×1
null ×1