简体   繁体   English

的IEqualityComparer <T> 不适用于&#39;Contains&#39;方法

[英]IEqualityComparer<T> not working for 'Contains' method

Okay, so I have the following classes/interfaces 好的,所以我有以下类/接口

FilterFileViewModel , CategoryViewModel , IFilterViewModel , ICategoryViewModel . FilterFileViewModelCategoryViewModelIFilterViewModelICategoryViewModel

Inheritance is set up as follows: 继承设置如下:

IFilterViewMode : IEqualityComparer<IFilterViewModel>
ICategoryViewModel : IFilterViewModel
FilterViewModel : ViewModel, IFilterViewModel
CategoryViewModel :FilterViewModel, ICategoryViewModel

And I have implemented IEqualityComparer in the abstract class FilterViewModel . 我在抽象类FilterViewModel实现了IEqualityComparer

Now, I have an IEnumerable<ICategoryViewModel> , but if I call "Contains" on it, it doesn't seem to use the Equals method I have implemented at FilterViewModel . 现在,我有一个IEnumerable<ICategoryViewModel> ,但是如果我在其上调用“Contains”,它似乎不会使用我在FilterViewModel实现的Equals方法。

I can see that it's most likely because ICategoryViewModel doesn't have the Equals method... so the only solution I can think of is to have a collection of IEnumerable<CategoryViewModel> instead, but this isn't ideal. 我可以看到它最有可能是因为ICategoryViewModel没有Equals方法......所以我能想到的唯一解决方案是拥有IEnumerable<CategoryViewModel>的集合,但这并不理想。

Can anyone think of a better way to structure this? 任何人都可以想到一个更好的结构方法吗?

You seem to misunderstand the purpose of IEqualityComparer<IFilterViewModel> interface. 您似乎误解了IEqualityComparer<IFilterViewModel>接口的用途。 It is not common to implement it in your model objects. 在模型对象中实现它并不常见。 Rather, you implement it in a special helper class, and use it to tweak the interpretation of equality in situations when you need that. 相反,您可以在一个特殊的帮助器类中实现它,并在需要时使用它来调整相等的解释。 This is usually done in situations when you have no control over the Equals method of the class. 这通常在您无法控制类的Equals方法的情况下完成。

If you want classes themselves to know how to compare for equality, you need to override Equals and GetHashCode methods on the classes themselves. 如果您希望类本身知道如何比较相等性,则需要在类本身上重写EqualsGetHashCode方法。 If you want to force subclasses to supply type-specific Equals , use IEquatable<T> interface: 如果要强制子类提供特定于类型的Equals ,请使用IEquatable<T>接口:

IFilterViewMode : IEquatable<IFilterViewModel>

Note: Don't forget to implement GetHashCode even if your current code path does not require it. 注意:即使您当前的代码路径不需要,也不要忘记实现GetHashCode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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