简体   繁体   English

对象的通用列表包含返回 false

[英]generic list of objects contains short returning false

I am working on a project and i have to check for some values of type short in a generic list of object.我正在做一个项目,我必须在 object 的通用列表中检查一些 short 类型的值。 Strangely I noticed that it is always returning false even if there is that value in the generic list of objects.奇怪的是,我注意到它总是返回 false,即使在通用对象列表中有该值。 I am providing a small piece of code which replicates that scenario in my project.我正在提供一小段代码,它在我的项目中复制了该场景。

List<object> objectList = new List<object>();
objectList.Add(1);
objectList.Add(2);
objectList.Add(3);
if (objectList.Contains(1))
{
    short i = 1;
    if (objectList.Contains(i))
    {
    }
    else if (objectList.Contains(i.ToString()))
    {
    }
    else
    {
        //Entering this else this loop only
    }
}

My assumption is because of the difference in the size for those types it may be returning false.我的假设是因为这些类型的大小不同,它可能返回错误。 Any other thoughts.任何其他想法。

Thanks.谢谢。

objectList.Add(1);

is the same as是相同的

int i = 1;
objectList.Add(i);

So所以

int y = 1;
objectList.Contains(y); // true

short z = 1;
objectList.Contains(z); // false

You are adding boxed Integer objects to the list, then seeing if a boxed short or string version of the number is in the list, both of which are going to be false because they're different types.您将盒装 Integer 对象添加到列表中,然后查看数字的盒装短版或字符串版本是否在列表中,这两者都将是错误的,因为它们是不同的类型。

Try casting your short to an int in the first test.尝试在第一次测试中将你的 short 转换为 int。 Why did you choose to not use generic <int> and skip the boxing/unboxing?为什么您选择不使用通用<int>并跳过装箱/拆箱?

short is an object type so by default it would only be equal to it's own instance. short 是一个 object 类型,所以默认情况下它只等于它自己的实例。 This equality has been overriden inside the framework as such:这种相等性已在框架内被覆盖,如下所示:

public override bool Equals(object obj)
{
  if (!(obj is short))
    return false;
  else
    return (int) this == (int) (short) obj;
}

Not how you and me would have expected it:)不是你和我所期望的:)

It is even more unexpected than you would think.这比你想象的更出乎意料。 Take the following cases:采取以下情况:

int i = 1;
short s = 1;
System.Console.WriteLine(i==s ? "Yes" : "No"); // Yes
System.Console.WriteLine(i.CompareTo(s)==0 ? "Yes" : "No"); // Yes
System.Console.WriteLine(s.CompareTo(i) == 0 ? "Yes" : "No"); // ERROR !
System.Console.WriteLine(s.Equals(i) ? "Yes" : "No"); // No
System.Console.WriteLine(i.Equals(s) ? "Yes" : "No"); // Yes

Not very consistent en predicatable不是很一致 en 可预测的

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

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