等于,GetHashCode,EqualComparers和模糊相等 [英] Equals, GetHashCode, EqualityComparers and fuzzy equality

查看:106
本文介绍了等于,GetHashCode,EqualComparers和模糊相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于具有属性A,B,C,D,StartDate和EndDate的对象,如果我想实现一些对象,如果两个对象具有相同的A,B和C且日期范围重叠,则该对象相等?



我尝试过创建这样的EqualityComparer

 公共替代bool Equals(RateItem x,RateItem y)
{
bool equal = true;
if(((xA!= yA || xB!= yB || xC!= yC ||
(x.StartDate< y.StartDate&&&x; EndDate< = y。 StartDate)||
(x.StartDate> y.StartDate&&y.EndDate< = x.StartDate)))
{equal = false; }
返回等于;
}

但是,框架中的很多地方似乎忽略了Equals并使用GetHashCode和对此文件还不清楚。当我去实现GetHashCode时,我不知道如何使HashCodes变得一样而不忽略日期。



要使其更加具体,这与项目管理和费率有关。我想实施一项业务规则,即同一项目中同一角色,同一角色的同一个人在同一时期内不必设置不同的费率。因此,在担任DBA角色的Project DeathMarch项目中,Bob在任何给定时间只能记录一个有效的账单率。如果他需要在同一时间段内以不同的速度记录QA分析师的几个小时,那可以。这是一个庞大的预先存在的系统,因此不能选择更改域对象的结构。

解决方案

这是不可能的。 / p>

.Net中的平等必须是可传递的,这意味着如果 a == b b == c ,然后 a == c


For an object with properties A, B, C, D, StartDate and EndDate if I wanted to implement something where any two objects are equal if they have identical A, B and C and overlapping date range, how would that be done?

I have tried creating an EqualityComparer like so

    public override bool Equals(RateItem x, RateItem y)
    {
        bool equal = true;
        if ((x.A != y.A || x.B != y.B || x.C != y.C ||
            (x.StartDate < y.StartDate && x.EndDate <= y.StartDate) ||
            (x.StartDate > y.StartDate && y.EndDate <= x.StartDate)))
        { equal = false; }
        return equal;
    }

But it seems lots of places in the framework ignore Equals and use GetHashCode and the documentation is not clear on that at all. When I go to implement GetHashCode I don't know how to make the HashCodes turn out the same without ignoring the dates.

To make it a little more concrete this has to do with project management and rates. I want to implement a business rule that the same person on the same project in the same role can't have to different rates during the same time period. So Bob on Project DeathMarch in the role of DBA can only have one effective bill rate at any given time to log his time. If he needed to log some hours in the role of QA analyst at a different rate during the same time period that is OK. This is a massive pre-existing system so changing the domain object structure is not an option.

解决方案

This is not possible.

Equality in .Net must be transitive, meaning that if a == b and b == c, then a == c.

这篇关于等于,GetHashCode,EqualComparers和模糊相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆