本文介绍了为什么要实施的IEquatable< T>接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读文章,理解在一定程度上接口但是,如果我想立刻我自己的自定义equals方法,看来我可以做到这一点没有实现IEquatable接口。一个例子。

 使用系统;
System.Collections中使用;
使用System.ComponentModel;命名空间ProviderJSONConverter.Data.Components
{
    公共类地址:IEquatable<地址>
    {
        公共字符串的地址{搞定;组; }        [默认值()]
        公共字符串address_2 {搞定;组; }
        公共字符串城市{搞定;组; }
        公共字符串状态{搞定;组; }
        公共字符串拉链{搞定;组; }        公共布尔等于(地址等)
        {
            如果(Object.ReferenceEquals(其他,NULL))返回false;
            如果(Object.ReferenceEquals(这一点,其他))返回true;
            回报(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<地址> 出code,似乎应用程序来操作完全一样。因此,我不清楚为什么实现接口?我可以写我自己的自定义equals方法没有它和断点将仍然打的方法和给回相同的结果。
任何人都可以帮助解释这个给我吗?我挂了,为什么有 IEquatable<地址> 之前调用Equals方法


解决方案

Well, that depends on what "the application" does. For example:

List<Address> addresses = new List<Address>
{
    new Address { ... }
};
int index = addresses.IndexOf(new Address { ... });

... that won't work (i.e. index will be -1) if you have neither overridden Equals(object) nor implemented IEquatable<T>. List<T>.IndexOf won't call your Equals overload.

Code that knows about your specific class will pick up the Equals overload - but any code (e.g. generic collections, all of LINQ to Objects etc) which just works with arbitrary objects won't pick it up.

这篇关于为什么要实施的IEquatable&LT; T&GT;接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 23:54