包含总是错误的,因为引用不一样?
我正在实现一个应用程序,您必须在其中验证某个对象是否在列表中。我知道 .contains
会发生这种情况,但我用 XML 文件填充列表,然后检查列表是否包含此文件的对象是新创建的,因此引用不相同,并且.Contains
始终为 false。
有人知道解决这个问题吗?代码如下:
if (qfs.Contains(exa.Question.File))
{
booleansQuestionFile[i] = true;
}
if
语句始终为 false。
I am implementing an application, in which you have to validate if some object is in a list. This happens with .contains
I know, but I fill up my list with an XML file, and then the object which I check if the list contains this, is newly created so the references are not the same and .Contains
will always be false.
Someone who knows to fix this problem? This is the code:
if (qfs.Contains(exa.Question.File))
{
booleansQuestionFile[i] = true;
}
The if
statement is always false.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如文档中所述,
包含
使用默认的相等比较器。要更改默认行为,请让您的类实现IEquatable
或覆盖
等于
。As described in the documentation,
Contains
uses the default equality comparer. To change the default behavior, make your class implementIEquatable<T>
or overrideEquals
.您应该重写 Equals 方法您可以定义两个对象何时相同的方式。
You should override the Equals method That way you can define when two objects are the same.
存储在列表中的对象应该实现 IEquatable。这样,引用不同并不重要,它仍然会正确地比较它们是否相等。
以下是显示示例的文章链接。这个 博客文章有更多细节。
The objects that are stored in the list should implement IEquatable. This way it does not matter that the references are different it will still compare them for equality properly.
Here is a link to an article that shows an example. And this blog post goes into more detail.
您也可以使用这样的代码,它将节省您更改类的需要:
You can also have such code instead, it will save you the need to change the class: