本文介绍了LINQ和放大器;层次分明,实现equals和放大器; gethash code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我努力使这项工作,我似乎无法知道为什么它不能正常工作
so I'm trying to make this work and I can't seem to know why it doesn't work
演示code;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var myVar = new List<parent >();
myVar.Add(new parent() { id = "id1", blah1 = "blah1", c1 = new child() { blah2 = "blah2", blah3 = "blah3" } });
myVar.Add(new parent() { id = "id1", blah1 = "blah1", c1 = new child() { blah2 = "blah2", blah3 = "blah3" } });
var test = myVar.Distinct();
Console.ReadKey();
}
}
public class parent : IEquatable<parent>
{
public String id { get;set;}
public String blah1 { get; set; }
public child c1 { get; set; }
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + id.GetHashCode();
hash = hash * 23 + blah1.GetHashCode();
hash = hash * 23 + (c1 == null ? 0 : c1.GetHashCode());
return hash;
}
}
public bool Equals(parent other)
{
return object.Equals(id, other.id) &&
object.Equals(blah1, other.blah1) &&
object.Equals(c1, other.c1);
}
}
public class child : IEquatable<child>
{
public String blah2 { get; set; }
public String blah3 { get; set; }
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + blah2.GetHashCode();
hash = hash * 23 + blah3.GetHashCode();
return hash;
}
}
public bool Equals(child other)
{
return object.Equals(blah2, other.blah2) &&
object.Equals(blah3, other.blah3);
}
}
}
任何人都可以发现我的错误(S)?
anyone could spot my error(s) ?
推荐答案
您需要重写等于(对象)
方法:
public override bool Equals(object obj) {
return Equals(obj as parent);
}
在的Object.Equals
办法(不像 EqualityComparer&LT; T&GT; .DEFAULT
)不使用 IEquatable
接口。因此,当你写的Object.Equals(C1,other.c1)
,它不会打电话给你的 Child.Equals(儿童)
方法。
The object.Equals
method (unlike EqualityComparer<T>.Default
) does not use the IEquatable
interface. Therefore, when you write object.Equals(c1, other.c1)
, it doesn't call your Child.Equals(Child)
method.
您没有绝对需要做的父
为好,但您真的应该的。
You don't absolutely need to do that for parent
as well, but you really should.
这篇关于LINQ和放大器;层次分明,实现equals和放大器; gethash code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!