我有一个名为'x'的类,它覆盖Equals(),如下所示:
public override bool Equals(object obj)
{
if(obj is x)
{
return ((obj as x).key == this.key);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
当以下扩展方法尝试使用上面的覆盖进行比较时,不会使用Equals():
public static bool Contains(this HashSet<x> set, char key)
{
x SearchKey = new x(key);
return set.Contains(SearchKey);
}
Run Code Online (Sandbox Code Playgroud)
只有当我修改extensio方法中的第一行时,我才会得到预期的行为,如下所示:
x SearchKey = new x(key);
Run Code Online (Sandbox Code Playgroud)
你能解释一下这种行为吗?
我曾经预料到,Equals()将被调用x本身的实例,因为它是Object的一个子集.我错过了什么?
您可能必须重写 GetHashCode ;) 在 hashSet 中,比较方法是 hashcode。
| 归档时间: |
|
| 查看次数: |
2521 次 |
| 最近记录: |