何时使用IEquatable< T>又为什么 [英] When To Use IEquatable<T> And Why

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

问题描述

IEquatable< T>是什么? 可以买给您吗?我看到它有用的唯一原因是在创建泛型类型并强迫用户实现和编写良好的equals方法时。

What does IEquatable<T> 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.

我缺少什么?

推荐答案

MSDN


IEquatable(T)接口由通用集合对象使用,例如 Dictionary(TKey,TValue) List(T) ,以及 LinkedList(T),当使用包含 IndexOf LastIndexOf 删除

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.

IEquatable< T> 的实现将减少这些类的类型转换,因此会稍快一些而不是标准的 object.Equals 方法。例如,请查看两种方法的不同实现:

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&lt; T&gt;又为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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