且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IEquatable,如何正确实施

更新时间:2023-01-26 10:13:41

您可以使用LINQ使用标准的自定义谓词来检查列表中是否包含项。在这种情况下,您无需覆盖等于或实现 IEquatable

You can check if your list contains an item using a custom predicate for the criteria, using LINQ. In that case you don't need to override Equals nor implement IEquatable:

// check if the list contains an item with a specific ID
bool found = someList.Any(item => item.ID == someId);

覆盖等于(其中 GetHashCode )和实现 IEquatable 很有用,如果您需要将项目存储在 Dictionary Hashtable

Overriding Equals (with GetHashCode) and implementing IEquatable is useful if you need to store your item in a Dictionary or a Hashtable.