【发布时间】:2014-02-21 10:41:52
【问题描述】:
我一直在阅读如何将列表与另一个列表进行比较。我试图实现IEquatable 接口。这是我到目前为止所做的:
/// <summary>
/// A object holder that contains a service and its current failcount
/// </summary>
public class ServiceHolder : IEquatable<ServiceHolder>
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="service"></param>
public ServiceHolder(Service service)
{
Service = service;
CurrentFailCount = 0;
}
public Service Service { get; set; }
public UInt16 CurrentFailCount { get; set; }
/// <summary>
/// Public equal method
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
ServiceHolder tmp = obj as ServiceHolder;
if (tmp == null)
{
return false;
}
else
{
return Equals(tmp);
}
}
/// <summary>
/// Checks the internal components compared to one annother
/// </summary>
/// <param name="serviceHolder"></param>
/// <returns>tru eif they are the same else false</returns>
public bool Equals(ServiceHolder serviceHolder)
{
if (serviceHolder == null)
{
return false;
}
if (this.Service.Id == serviceHolder.Service.Id)
{
if (this.Service.IpAddress == serviceHolder.Service.IpAddress)
{
if (this.Service.Port == serviceHolder.Service.Port)
{
if (this.Service.PollInterval == serviceHolder.Service.PollInterval)
{
if (this.Service.ServiceType == serviceHolder.Service.ServiceType)
{
if (this.Service.Location == serviceHolder.Service.Location)
{
if (this.Service.Name == this.Service.Name)
{
return true;
}
}
}
}
}
}
}
return false;
}
}
这就是我使用它的地方:
private void CheckIfServicesHaveChangedEvent()
{
IList<ServiceHolder> tmp;
using (var db = new EFServiceRepository())
{
tmp = GetServiceHolders(db.GetAll());
}
if (tmp.Equals(Services))
{
StateChanged = true;
}
else
{
StateChanged = false;
}
}
现在,当我调试并在 equals 函数中放置一个断点时,它永远不会被命中。
这让我认为我没有正确实现它或者我没有正确调用它?
【问题讨论】:
-
tmp是一个列表,而不是单个ServiceHolder。 -
我不能比较两个列表吗?
-
作为一般风格指南,避免使用像
tmp这样的变量名。如果你的变量是ServiceHolder类型,你可以称它为serviceHolder。如果它是ServiceHolder类型的对象的集合,则可以将其称为serviceHolders。起初,当我看到几个tmp时,我认为它们共享相同的类型。不应鼓励类型混淆。
标签: c# list compare equals iequatable