c# – 为什么不应该使用反射来实现Equals和GetHashCode?
发布时间:2020-12-15 04:01:34 所属栏目:百科 来源:网络整理
导读:我有一些对象有一堆字段,我发现自己必须实现GetHashCode和Equals.手动执行每个字段是很痛苦的,所以我写道: public override int GetHashCode(){ int hash = 17; foreach (PropertyInfo p in GetType().GetProperties()) { hash = hash * 23 + p.GetValue(th
我有一些对象有一堆字段,我发现自己必须实现GetHashCode和Equals.手动执行每个字段是很痛苦的,所以我写道:
public override int GetHashCode() { int hash = 17; foreach (PropertyInfo p in GetType().GetProperties()) { hash = hash * 23 + p.GetValue(this,null).GetHashCode(); } return hash; } public override bool Equals(object obj) { foreach (PropertyInfo p in GetType().GetProperties()) { if (p.GetValue(obj,null) != p.GetValue(this,null)) return false; } return true; } 除了速度考虑,为什么我不应该这样实现? 解决方法
这是我避免这条路线的几个原因
比较字段而不是属性更可靠 下面是一个类型的具体示例,这将在应用程序中引起无限递归 class C1 { public object Prop1 { get; set; } }; var local = new C1(); local.Prop1 = local; var x = local.GetHashCode(); // Infinite recursion (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |