何时使用IEquatable以及为什么 [英] When To Use IEquatable And Why

查看:407
本文介绍了何时使用IEquatable以及为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是不明白这一点 - 这是什么IEquatable买你到底??



唯一的原因,我可以看到它是有用的创建是当一个泛型类型,并迫使用户实施和写一个好的equals方法。



我缺少什么


解决方案

MSDN



<作为含有,的IndexOf,LastIndexOf平等在这样的方法测试当p>的的IEquatable(T)接口使用泛型集合对象,例如词典(TKEY的,TValue),表(T),和LinkedList(T)和删除



IEquatable< T> 实施将需要这些类少了一个演其结果将是比标准的Object.Equals 方法,将被以其他方式使用稍快。作为一个例子看到不同的实现这两种方法:

 公共布尔等于(T除外)
{
如果(其他== NULL)
返回false;

回报率(this.Id == other.Id);
}

公众覆盖布尔等于(obj对象)
{
如果(OBJ == NULL)
返回FALSE;
$ B $(B T)= tObj OBJ为T; //额外投
如果(tObj == NULL)
返回false;
,否则
返回this.Id == tObj.Id;
}


I just dont understand this - What does IEquatable buy you exactly??

The only reason I can see it being useful is when creating a generic type and forcing users to implement and write a good equals method.

What am I missing

解决方案

From the msdn:

The IEquatable(T) interface is used by generic collection objects such as Dictionary(TKey, TValue), List(T), and LinkedList(T) when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove.

The IEquatable<T> implementation will require one less cast for these classes and as a result will be slightly faster than the standard object.Equals method that would be used otherwise. As an example see the different implementation of the two methods:

public bool Equals(T other) 
{
  if (other == null) 
     return false;

  return (this.Id == other.Id);
}

public override bool Equals(Object obj)
{
  if (obj == null) 
     return false;

  T tObj = obj as T;  // The extra cast
  if (tObj == null)
     return false;
  else   
     return this.Id == tObj.Id;
}

这篇关于何时使用IEquatable以及为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆