I want my Food class to be able to test whenever it is equal to another instance of Food. I will later use it against a List, and I want to use its List.Contains() method. Should I implement IEquatable<Food> or just override Object.Equals()? From MSDN:

This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).

So my next question is: which functions/classes of the .NET framework make use of Object.Equals()? Should I use it in the first place?

推荐答案

The main reason is performance. When generics were introduced in .NET 2.0 they were able to add a bunch of neat classes such as List<T>, Dictionary<K,V>, HashSet<T>, etc. These structures make heavy use of GetHashCode and Equals. But for value types this required boxing. IEquatable<T> lets a structure implement a strongly typed Equals method so no boxing is required. Thus much better performance when using value types with generic collections.

Reference types don't benefit as much but the IEquatable<T> implementation does let you avoid a cast from System.Object which can make a difference if it's called frequently.

As noted on Jared Parson's blog though, you must still implement the standard Object.Equals and Object.GetHashcode overrides.

.net相关问答推荐

使用.NET 8时无法识别运行标识符

C#:如何构造异步/等待代码,其中许多请求是针对相同的、返回缓慢的数据发出的,这可以满足所有请求

cmd 冻结中的 dotnet 命令.怎么了?

如何确定计时器是否正在运行?

如何计算给定2个字符串的距离相似性度量?

如何为多种文件类型设置 FileSystemWatcher 过滤器?

为什么不能使用 null 作为 Dictionary 的键?

从 switch 块中跳出 foreach 循环

抛出 ArgumentNullException

我可以使用 UriTemplate 将非字符串传递给 WCF RESTful 服务吗?

BackgroundWorker 中未处理的异常

无法将文件 *.mdf 作为数据库附加

公钥令牌的作用是什么?

向 .NET 应用程序添加脚本功能

如何在 Action 中传递参数?

如何防止任务的同步延续?

场与财产.性能优化

C# 相当于 Java 的 Exception.printStackTrace()?

多个列表与 IEnumerable.Intersect() 的交集

C# 应用程序中的资源和嵌入式资源有什么区别?