我一直在閱讀如何比較一個列表和一個別的。我試圖實現IEquatable
接口。以下是我迄今所做的:比較一個列表<T>與另一個列表<t>
/// <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;
}
}
現在,當我調試,我把一個破發點中的等號功能它從來沒有被擊中。
這讓我覺得我實現了它不正確或我沒有正確調用它?
'tmp'是一個不是單個'ServiceHolder'的列表。 –
我不能比較兩個列表嗎? – Zapnologica
作爲一般的風格準則,避免使用像'tmp'這樣的變量名。如果你的變量的類型是'ServiceHolder',你可以把它叫做'serviceHolder'。如果它是「ServiceHolder」類型的對象的集合,則可以將其稱爲「serviceHolders」。起初,當我看到幾個'tmp'時,我認爲他們共享相同的類型。不應鼓勵類型混淆。 – dureuill