各位专家早上好,
我有一个组合框,其中填充了类类型值。
我的类(class)名称是汽车。
public string Description;
public long Id;
我加载组合框的函数是
foreach(Cars car in CarList)
{
comboCars.Items.Add(car);
}
我有一个功能需要在该组合框中搜索汽车,我有这段代码。
public void setCarCmb(long id)
{
for (int i = 0; i < comboCars.Items.Count; i++)
{
if (((Cars)comboCars.Items[i]).Id == id)
{
comboCars.SelectedIndex = i;
comboCars.Enabled = false;
break;
}
}
}
这有效,但我试图找到更好更快的方法,我尝试使用
public void setCarCmb(Cars car)
{
comboCars.SelectedIndex = comboCars.Items.IndexOf(car);
comboCars.Enabled = false;
}
但是返回的索引始终是-1,似乎出了什么问题?
最佳答案
线路
comboCars.SelectedIndex = comboCars.Items.IndexOf(car);
尝试查找 car
的索引组合框项目中的对象。然而,仅仅因为两个对象具有相同的属性值,并不意味着它们是同一个对象。以下面的例子为例。
Car car1 = new Car() { Id = 1, Description = "MyCar" };
Car car2 = new Car() { Id = 1, Description = "MyCar" };
bool equality = car1 == car2;
此代码将返回 false
,因为虽然这两个对象的内容相同,但它们仍然是两个不同的对象。
您的 IndexOf()
也会发生同样的情况比较,并且由于它找不到您在组合框中传递的对象,因此它返回 -1
这意味着“不匹配”。
注意:
您在工作示例中查找对象的方式很好。
注2:
如果你确实想使用像 SetCarCmb
这样的方法,您可以实现IEquatable<T>
您的Car
中的界面像这样的类:
public class Car : IEquatable<Car>
{
public string Description;
public long Id;
public bool Equals(Car other)
{
// Choose what you want to consider as "equal" between Car objects.
// For example, equality of ID means two objects are equal in this example.
if (other == null)
return false;
return Id == other.Id;
}
}
现在不再比较两个对象引用,IndexOf()
方法将使用此比较器来比较 Car
的两个对象类(class)。因此,您将像这样修改您的方法:
public static void SetCarCmb(Car car)
{
comboCars.SelectedIndex = comboCars.Items.Cast<Car>().ToList().IndexOf(car);
comboCars.Enabled = false;
}
但实际上,没有必要陷入所有这些麻烦。您的第一个方法应该可以正常工作,特别是考虑到组合框不太可能包含数千个项目,并且效率根本不应该成为问题。
关于C# 按对象搜索组合框的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51661860/