【发布时间】:2012-04-01 15:10:56
【问题描述】:
User.ID 和 Group.ID 都是 Int16 且不可变的,我想生成最佳的 HashCode。
这就是平等
public override bool Equals(Object obj)
{
//Check for null and compare run-time types.
if (obj == null || GetType() != obj.GetType()) return false;
UserGroup item = (UserGroup)obj;
return (User.ID == item.User.ID && Group.ID == item.Group.ID);
}
什么是最佳的 GetHashCode。现在我正在使用以下内容,但这只是因为我将其视为示例。 Object 的主要用途是在 HashSet 中,HashSet 有很多 .Select(x => x.User.ID = y) 或 .Select(x => x.Group.ID = y)。
public override int GetHashCode() { return (int)User.ID ^ (int)Group.ID; }
【问题讨论】:
-
请写
GetType() != obj.GetType(),而不是!(obj is UserGroup)。