What's the recommended best practice for using IEqualityComparer?

前端 未结 6 1092
栀梦
栀梦 2020-12-30 09:33

I\'m looking for real world best practices, how other people might have implemented solutions with complex domains.

6条回答
  •  不思量自难忘°
    2020-12-30 09:59

    This is what MSDN has to say about IEqualityComparer (non-generic):

    This interface allows the implementation of customized equality comparison for collections. That is, you can create your own definition of equality, and specify that this definition be used with a collection type that accepts the IEqualityComparer interface. In the .NET Framework, constructors of the Hashtable, NameValueCollection, and OrderedDictionary collection types accept this interface.

    This interface supports only equality comparisons. Customization of comparisons for sorting and ordering is provided by the IComparer interface.

    It looks like the generic version of this interface performs the same function but is used for Dictionary<(Of <(TKey, TValue>)>) collections.

    As far as best practices around using this interface for your own purposes. I would say that the best practice would be to use it when you are deriving or implementing a class that has similar functionality to the above mentioned .NET framework collections and where you want to add the same capability to your own collections. This will ensure that you are consistent with how the .NET framework uses the interface.

    In other words support the use of this interface if you are developing a custom collection and you want to allow your consumers to control equality which is used in a number of LINQ and collection related methods (eg. Sort).

提交回复
热议问题