当我使用 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.Equals
和 Object.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/