我正在添加项目,ListBox所以:
myListBox.Items.addRange(myObjectArray);
Run Code Online (Sandbox Code Playgroud)
我还想选择以下添加的一些项目:
foreach(MyObject m in otherListOfMyObjects)
{
int index = myListBox.Items.IndexOf(m);
myListBox.SelectedIndices.Add(index);
}
Run Code Online (Sandbox Code Playgroud)
但index总是如此-1.
是否有不同的方法来获取对象的索引ListBox?
你应该确保MyObject覆盖Equals(),GetHashCode()并且ToString()使该IndexOf()方法能够正确地找到对象.
从技术上讲,ToString()不需要重写相等性测试,但它对调试很有用.