I have this simple class with those 2 enum fields, I'm trying to find one item of this object in a collection (List<T>
) but the Contains methods doesn't works correctly
public class Calculator : IEqualityComparer<Calculator>
{
public DashboardsComputationMode ComputationMode { get; set; }
public Modes Mode { get; set; }
public Calculator(DashboardsComputationMode dashboardsComputationMode, Modes mode)
{
ComputationMode = dashboardsComputationMode;
Mode = mode;
}
public bool Equals(Calculator x, Calculator y)
{
return (x.ComputationMode.Equals(y.ComputationMode) && x.Mode.Equals(y.Mode));
}
public int GetHashCode(Calculator obj)
{
return obj.ComputationMode.GetHashCode() ^ obj.Mode.GetHashCode();
}
}
public enum DashboardsComputationMode
{
Weighted = 0,
Aggregated = 1,
PR = 2,
CurrentValue = 3,
EquivalentHours = 4,
AggregatedCorrected = 5,
PRCorrected = 6
}
public enum Modes
{
InstantaneousMode = 0,
DailyMode = 1,
MonthlyMode = 2,
YearlyMode = 5,
Undefined = 4,
}
Why could be that this test doesn't works
[TestMethod]
public void TestMethod1()
{
var list = new List<Calculator>()
{
new Calculator(DashboardsComputationMode.PR, Modes.DailyMode),
new Calculator(DashboardsComputationMode.CurrentValue, Modes.YearlyMode),
new Calculator(DashboardsComputationMode.PRCorrected, Modes.MonthlyMode)
};
var item = new Calculator(DashboardsComputationMode.CurrentValue, Modes.YearlyMode);
Assert.IsTrue(list[1].Equals(item));
Assert.IsTrue(list.Contains(item));
}
The first assert works fine
Assert.IsTrue(list[1].Equals(item))
but the second doesn't
Assert.IsTrue(list.Contains(item));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…