我的理解是,GetHashCode将为共享相同值的两个不同实例返回相同的值。 MSDN文档在这一点上有点模糊。当两个相同类型的对象具有相同的值时,为什么hashcode不同?
哈希码是一个数值,用于在进行相等测试期间识别对象 。
如果我有两个相同类型的实例和相同的值将GetHashCode()返回相同的值?
假设所有的值都是一样的,下面的测试过去还是失败?
SecurityUser只有getter和setter;
[TestMethod]
public void GetHashCode_Equal_Test()
{
SecurityUser objA = new SecurityUser(EmployeeName, EmployeeNumber, LastLogOnDate, Status, UserName);
SecurityUser objB = new SecurityUser(EmployeeName, EmployeeNumber, LastLogOnDate, Status, UserName);
int hashcodeA = objA.GetHashCode();
int hashcodeB = objB.GetHashCode();
Assert.AreEqual<int>(hashcodeA, hashcodeB);
}
/// <summary>
/// This class represents a SecurityUser entity in AppSecurity.
/// </summary>
public sealed class SecurityUser
{
#region [Constructor]
/// <summary>
/// Initializes a new instance of the <see cref="SecurityUser"/> class using the
/// parameters passed.
/// </summary>
/// <param name="employeeName">The employee name to initialize with.</param>
/// <param name="employeeNumber">The employee id number to initialize with.</param>
/// <param name="lastLogOnDate">The last logon date to initialize with.</param>
/// <param name="status">The <see cref="SecurityStatus"/> to initialize with.</param>
/// <param name="userName">The userName to initialize with.</param>
public SecurityUser(
string employeeName,
int employeeNumber,
DateTime? lastLogOnDate,
SecurityStatus status,
string userName)
{
if (employeeName == null)
throw new ArgumentNullException("employeeName");
if (userName == null)
throw new ArgumentNullException("userName");
this.EmployeeName = employeeName;
this.EmployeeNumber = employeeNumber;
this.LastLogOnDate = lastLogOnDate;
this.Status = status;
this.UserName = userName;
}
#endregion
#region [Properties]
/// <summary>
/// Gets the employee name of the current instance.
/// </summary>
public string EmployeeName { get; private set; }
/// <summary>
/// Gets the employee id number of the current instance.
/// </summary>
public int EmployeeNumber { get; private set; }
/// <summary>
/// Gets the last logon date of the current instance.
/// </summary>
public DateTime? LastLogOnDate { get; private set; }
/// <summary>
/// Gets the userName of the current instance.
/// </summary>
public string UserName { get; private set; }
/// <summary>
/// Gets the <see cref="SecurityStatus"/> of the current instance.
/// </summary>
public SecurityStatus Status { get; private set; }
#endregion
}
哪里了'SecurityUser'类从何而来?可以在派生类中重写'GetHashCode'来返回任何东西。不能保证其实施是正确的。 – 2013-04-04 17:17:53
@RobertHarvey我不好,我应该指出,它不。 SecurityUser只有getter和setter。 – 2013-04-04 17:19:48