问题描述
我正在使用.net 2.0和c#,并且已经在我的类中实现了IEquatible接口,如下所示:-
I am using .net 2.0 and c# and I have implemented the IEquatible interface in my class like this:-
public MyClass() : IEquatable<MyClass>
{
Guid m_id = Guid.NewGuid();
public Guid Id
{
get
{
return m_id;
}
}
#region IEquatable<MyClass> Members
public bool Equals(MyClass other)
{
if (this.Id == other.Id)
{
return true;
}
else
{
return false;
}
}
#endregion
}
这是不好的编程习惯吗?我已经读到我还需要实现Object.Equals和Object.GetHashCode,但是我不确定为什么。
Is this bad programming practice? I've read that I also need to implement Object.Equals and Object.GetHashCode as well, but I am not sure why.
我希望能够检查MyClass实例是否尚未包含在MyClass类型的通用列表中。为什么框架只建议您仅实现Equals?
I want to be able to check that an instance of MyClass is not already contained in a generic list of type MyClass. Why does the framework only suggests that you implement Equals only?
任何帮助将不胜感激。
推荐答案
您可以使用LINQ使用标准的自定义谓词来检查列表中是否包含项。在这种情况下,您无需覆盖等于
或实现 IEquatable
:
You can check if your list contains an item using a custom predicate for the criteria, using LINQ. In that case you don't need to override Equals
nor implement IEquatable
:
// check if the list contains an item with a specific ID
bool found = someList.Any(item => item.ID == someId);
覆盖等于
(其中 GetHashCode
)和实现 IEquatable
很有用,如果您需要将项目存储在 Dictionary
或 Hashtable
。
Overriding Equals
(with GetHashCode
) and implementing IEquatable
is useful if you need to store your item in a Dictionary
or a Hashtable
.
这篇关于IEquatable,如何正确实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!