简体   繁体   中英

C# using two different equality comparers

I need to write a second equality comparer for a business object. It is a specialized equality comparer which is only applicable in certain situations. I do not want to override the Equal() because our persistent layer uses that to compare objects internally for its own uses. Let me give you an example of a class:

public class Product : BusinessObjectBase
{
    string Name  {get;set;}
    string Desc  {get;set;}
    double Price {get;set;}
} 

Since we mark the three properties as persistent data properties in our data access layer, the Equals() in the BusinessObjectBase compares those properties. Now, in a specific instance I would like to check if product A it equal to product B only be Name. I do not want to hardcode the actual property on the check because this property might change later.

While IComparer could be used here, but based on the description on MSDN, IComparer should be used not to equate items but to sort them, so that does not seem like a 100% correct answer. I would like to use something .NET already has and not create another interface. What is the best way to do this?

Thanks

您正在寻找IEqualityComparer<T>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM