据我了解,GetHashCode 将为共享相同值的两个不同实例返回相同的值。MSDN 文档在这一点上有点模糊。
哈希码是一个数值,用于在相等性测试期间识别对象。
如果我有两个相同类型的实例和相同的值,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
}