gpt4 book ai didi

c# - 何时使用 IEquatable 以及为什么

转载 作者:IT王子 更新时间:2023-10-29 03:59:43 25 4
gpt4 key购买 nike

什么是 IEquatable<T> 买你,到底?我认为它有用的唯一原因是在创建泛型类型并强制用户实现和编写良好的 equals 方法时。

我错过了什么?

最佳答案

来自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.

IEquatable<T>这些类的实现将需要更少的转换,因此将比标准 object.Equals 稍微快一点。否则将使用的方法。作为示例,请查看两种方法的不同实现:

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;
}

关于c# - 何时使用 IEquatable<T> 以及为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2476793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com