列表框包含找不到项目,无法删除项目 [英] Listbox contains does not find item, cannot remove an item

查看:58
本文介绍了列表框包含找不到项目,无法删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将项目添加到列表框中,如下所示:

I add items to a list box like so:

foreach(myObject object in ListOfObjects)
{
    mylistbox1.add(object);
}

foreach(myObject object in ListOfObjectsTwo)
{
    mylistbox2.add(object);
}

此外,我想在特定条件下删除几个项目.这就是我所做的:

Further on, I want to remove a couple of items given a specific condition. This is what I do:

foreach(myObject object in ListOfObjects3)
{
    mylistbox1.items.remove(object);
    mylistbox2.items.remove(object);
}

这似乎只适用于 mylistbox1 而不是 mylistbox2.当我调试时,我可以看到该项目在那里,并且它与我试图删除的项目具有完全相同的属性.当我尝试检查列表框是否包含我要删除的项目时,它返回 false.

This only seems to work for mylistbox1 but not mylistbox2. When I debug, I can see that the item is there and that it has the exact same properties as the one I'm trying to remove. When I try to check if the listbox contains the item im trying to remove, it returns false.

我似乎无法理解.

推荐答案

I c# 以某种方式比较对象所需的所有列表操作都使用 EqualsGetHashCode 方法.在您的情况下 Equals 和默认实现不会检查属性值,它只会验证作为参数对象传递的对象是否在列表中,因此请考虑您的列表中是否有相同的实例或仅发生了两个不同的实例具有相同的属性.(有用的 VS 选项是 make object id 它会用数字标记实例)

I c# all lists operation that are in some way required to compare objects use Equals or GetHashCode methods. In your case Equals and the default implementation wont check properties values it will only verify if the passed as argument object is in list so consider if you have the same instance in your list or just two different instances that happened to have the same properties. (the helpful VS option is make object id it will mark instance with a number)

如果是这种情况,那么您应该考虑覆盖 Equals 方法或找到要使用 linq 删除的实例,然后将该对象传递给 删除方法.

If this is the case then you should consider overriding Equals method or find the instance that you want to delete with linq for example and pas that object to Remove method.

这篇关于列表框包含找不到项目,无法删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆