gpt4 book ai didi

c# - IEqualityComparer 和 Contains 方法

转载 作者:可可西里 更新时间:2023-11-01 02:58:56 25 4
gpt4 key购买 nike

我有一个带有这 2 个枚举字段的简单类,我试图在集合 ( List<T> ) 中找到该对象的一项,但 Contains 方法无法正常工作

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,
}

为什么这个测试不起作用

[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));
}

第一个断言工作正常

Assert.IsTrue(list[1].Equals(item)) 

但是第二个没有

Assert.IsTrue(list.Contains(item));

最佳答案

List<T>.Contains 通过使用默认的相等比较器(由 EqualityComparer<T>.Default 返回的比较器)确定相等性。

这是关于如何 EqualityComparer<T>.Default 的 MSDN 解释作品:

The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

换句话说,你的 Calculator类应该实现 System.IEquatable (不是 System.IEqualityComparer !)接口(interface)或覆盖 Object.EqualsObject.GetHashCode方法。

关于c# - IEqualityComparer 和 Contains 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14580595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com