简体   繁体   English

包含总是假的,因为引用不一样?

[英]Contains is always false, because reference is not the same?

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. 这种情况发生在.contains我知道,但我用XML文件填充我的列表,然后我检查列表是否包含这个的对象是新创建的,因此引用不一样,并且.Contains将始终为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. if语句始终为false。

As described in the documentation , Contains uses the default equality comparer. 文档所述Contains使用默认的相等比较器。 To change the default behavior, make your class implement IEquatable<T> or override Equals . 要更改默认行为,请使您的类实现IEquatable<T>或覆盖Equals

您应该覆盖Equals方法 ,这样您就可以定义两个对象何时相同。

The objects that are stored in the list should implement IEquatable. 存储在列表中的对象应该实现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: 您也可以使用此类代码,它将为您节省更改类的需要:

if (qfs.Exists(f => f.Question.File.Equals(exa.Question.File)))
{
    booleansQuestionFile[i] = true;
}

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

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