c# - 如何使用其基类进行良好的平等比较?

标签 c# list abstract-class equals abstraction

当我使用 List.Contains(T item) 时,我正在尝试进行良好的比较。

问题是我将 BaseItem 用作列表项。我需要验证列表中的一个对象是否具有与我计划添加的对象相同的属性值。

例如:

public abstract class BaseItem
{
    // some properties

    public override bool Equals(object obj)
    {
        return obj != null && this.GetType() == obj.GetType();
    }
}

public class ItemA : BaseItem
{
    public int PropertyA { get; set; }

    public override bool Equals(object obj)
    {
        if (base.Equals(obj) == false)
            return false;

        return (this.PropertyA == (obj as ItemA).PropertyA;
    }
}

public class ItemB : BaseItem
{
    public int PropertyB { get; set; }

    public override bool Equals(object obj)
    {
        if (base.Equals(obj) == false)
            return false;

        return this.PropertyB == (obj as ItemB).PropertyB;
    }
}

public class Program
{
    static void Main(string[] args)
    {
        List<BaseItem> items = new List<BaseItem>()
        {
            new ItemB() { PropertyB = 3 },
            new ItemA() { PropertyA = 2 },
            new ItemB() { PropertyB = 2 }
        };

        BaseItem newItem = new ItemA() { PropertyA = 2 };
        items.Contains(newItem);  // should return 'True', because the first element is equals than 'newItem'
    }
}

我不确定重写 Equals 方法是否正确,或者我是否应该实现 IEquality 接口(interface)。

最佳答案

测试集合成员资格(列表成员资格、哈希集成员资格等)的标准方法是使用 .Contains 方法,该方法又使用 IEquatable<T>.Equals . IEquatable<T>.Equals 的默认实现(如果您不提供自己的实现)使用 Object.Equals(Object) ).

你当然可以实现IEquatable<T> .这将略微提高包含检查的性能。请参阅 msdn.microsoft.com/en-us/library/ms131190.aspx。

如果你实现 IEquatable<T>你仍然应该覆盖 Object.EqualsObject.GetHashCode提供一致的行为

If you implement Equals, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method.

http://msdn.microsoft.com/en-us/library/ms131190.aspx

有关相关讨论,请参阅此问题

Simplify Overriding Equals(), GetHashCode() in C# for Better Maintainability

关于c# - 如何使用其基类进行良好的平等比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11546079/

相关文章:

c# - Visual Studio 2005 缓慢关闭

c# - C# Windows 应用程序中按钮的热键

c# - .NET MVC 使用 ajax 将多个参数发布到 Controller

C# List IList 或 IEnumerable 作为参数

c++ - 我应该初始化抽象类的成员吗?

c# - 将 char*[] 从 c++ dll 结构传递到 c#

c# - 当我向数组添加某些内容时,它不会向列表添加任何内容

list - Lisp 列表操作问题

C# 抽象方法 : internally public and virtual?

java - java中的构造函数和抽象类