我一直在阅读文章并在一定程度上理解接口,但是,如果我想纠正我自己的自定义 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 方法,并且断点将仍然命中该方法并返回相同的结果。
谁能帮我解释一下吗?我很困惑为什么要包括“IEquatable<Address>
" 在调用 Equals 方法之前。
现在,如果我不实现该接口并将 : IEquatable 排除在代码之外,则应用程序的运行方式似乎完全相同。
嗯,这取决于“应用程序”的作用。例如:
List<Address> addresses = new List<Address>
{
new Address { ... }
};
int index = addresses.IndexOf(new Address { ... });
...那是行不通的(即index
将是 -1) 如果你没有重写Equals(object)
也没有实施IEquatable<T>
. List<T>.IndexOf
不会打电话给你的Equals
超载。
了解您的代码specific类将拿起Equals
重载 - 但任何适用于的代码(例如泛型集合、所有 LINQ to Objects 等)随意的物体不会拾取它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)