generic list of objects contains short returning false

让人想犯罪 __ 提交于 2019-12-11 07:50:11

问题


I am working on a project and i have to check for some values of type short in a generic list of object. Strangely I noticed that it is always returning false even if there is that value in the generic list of objects. 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.


回答1:


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



回答2:


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.

Try casting your short to an int in the first test. Why did you choose to not use generic <int> and skip the boxing/unboxing?




回答3:


short is an object type so by default it would only be equal to it's own instance. 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



来源:https://stackoverflow.com/questions/6780002/generic-list-of-objects-contains-short-returning-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!