何时使用IEquatable< T>又为什么

编程入门 行业动态 更新时间:2024-10-16 16:54:27
本文介绍了何时使用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;又为什么

本文发布于:2023-11-02 16:59:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552926.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:又为   amp   IEquatable   gt   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!