我编写了一段代码来检查对象相等性。 我引用了堆栈溢出本身的问题之一。 现在,即使我们有两个不同的对象,这段代码也会给出 true 。 有人能解释一下为什么吗?
using System;
namespace ConsolePractice
{
public class Test
{
public int Value { get; set; }
public string String1 { get; set; }
public string String2 { get; set; }
public override int GetHashCode()
{
int hash = 19;
hash = hash * 31 + Value;
hash = hash * 31 + String1.SafeGetHashCode();
hash = hash * 31 + String2.SafeGetHashCode();
return hash;
}
public override bool Equals(object obj)
{
Test test = obj as Test;
if (obj == null)
{
return false;
}
return Value == test.Value &&
String1 == test.String1 &&
String2 == test.String2;
}
}
class Demo
{
static void Main()
{
Test p1 = new Test
{
Value = 10,
String1 = "Test1",
String2 = "Test2"
};
Test p2 = new Test
{
Value = 10,
String1 = "Test1",
String2 = "Test2"
};
bool areEqual = p1.Equals(p2);
Console.WriteLine(areEqual.ToString());
Console.ReadLine();
}
}
}
在我的UtilityClass
static class utility
{
public static int SafeGetHashCode<T>(this T value) where T : class
{
return value == null ? 0 : value.GetHashCode();
}
}
没有成功后,我尝试了下面的代码,它也返回 true。 我在这里犯了什么错误?请帮忙
using System;
using System.Collections.Generic;
class ThingEqualityComparer : IEqualityComparer<Thing>
{
public bool Equals(Thing x, Thing y)
{
if (x == null || y == null)
return false;
return (x.Id == y.Id && x.Name == y.Name);
}
public int GetHashCode(Thing obj)
{
return obj.GetHashCode();
}
}
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
}
class Demo
{
static void Main()
{
Thing p1 = new Thing
{
Id = 10,
Name = "Test1",
};
Thing p2 = new Thing
{
Id = 10,
Name = "Test1",
};
var comparer = new ThingEqualityComparer();
Console.WriteLine(comparer.Equals(p1, p2));
Console.ReadLine();
}
}
最佳答案
您可以重写 Equals()
和 GetHashCode()
来定义“等于”在给定上下文中的含义。
您的等于
:
Test test = obj as Test;
if (obj == null)
{
return false;
}
return Value == test.Value &&
String1 == test.String1 &&
String2 == test.String2;
有一个错误,它应该是 if(test == null) return false;
但否则它会说“两个 Test
对象是相同的,如果它们具有Value
、String1
和 String2
相同,否则它们不是。您的 GetHashCode()
与此一致。
因此,代码返回 true
并不是一个错误:
Now this code is giving true even if we have two different objects.
是的,两个不同的相等对象。
如果您希望 Equals
和 GetHashCode()
告诉您它们是否是相同对象(即,对于一个对象类仅等于其自身),那么根本不重写 Equals
和 GetHashCode
;保持默认行为。
关于c# - 使用哈希码进行对象比较-概念困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31919567/