我一直在阅读有关接口的文章,并且了解了它们一定程度上的用法。然而,如果我想编写自己的自定义Equals方法,似乎可以不必实现IEquatable接口。以下是一个示例。
using System;
using System.Collections;
using System.ComponentModel;
namespace ProviderJSONConverter.Data.Components
{
public class Address : IEquatable<Address>
{
public string address { get; set; }
[DefaultValue("")]
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public bool Equals(Address other)
{
if (Object.ReferenceEquals(other, null)) return false;
if (Object.ReferenceEquals(this, other)) return true;
return (this.address.Equals(other.address)
&& this.address_2.Equals(other.address_2)
&& this.city.Equals(other.city)
&& this.state.Equals(other.state)
&& this.zip.Equals(other.zip));
}
}
}
现在,如果我不实现接口并将
: IEquatable<Address>
从代码中删除,似乎应用程序的操作完全相同。因此,我不清楚为什么要实现该接口?我可以自己编写自定义Equals方法而不需要它,断点仍将命中该方法并返回相同的结果。有人能帮我更好地解释一下吗?我困惑于为什么在调用Equals方法之前要包含"
IEquatable<Address>
"。
Equals(object)
和GetHashCode
。 - Jon SkeetObject.Equals
,所以我认为这不是同一个问题。 - Jon SkeetEquals
方法,所以这不是一个重复的问题。 - ken2k