我的理解是,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