我有以下代码来查找 ColorItem
的索引List<ColorItem>
中的对象
//Get the index of the color item
var colorList = dialogViewModel.Items;
var colorItem = new ColorItem();
colorItem = sp.TileColorItem;
int index = colorList.IndexOf(colorItem);
即使列表中有一个匹配的对象,index
总是返回-1。我错过了什么?
最佳答案
List<T>.IndexOf
在列表中查找与您传递给它的值相等的项目。默认情况下,对于类,相等只是对象标识——所以两个不同的对象被视为不相等,无论它们的字段是什么。但是,您可以通过覆盖 Equals
来更改它方法。
如果ColorItem
是你自己的类(class),你绝对可以通过覆盖 Equals
来完成这项工作(和 GetHashCode
;未被 List<T>.IndexOf
使用,但应始终被覆盖以与 Equals
保持一致)适本地:
public sealed class ColorItem : IEquatable<ColorItem>
{
private readonly string text;
private readonly Color color;
public string Text { get { return text; } }
public Color Color { get { return color; } }
public ColorItem(string text, Color color)
{
this.text = text;
this.color = color;
}
public override bool Equals(object other)
{
return Equals(other as ColorItem);
}
public bool Equals(ColorItem otherItem)
{
if (otherItem == null)
{
return false;
}
return otherItem.Text == text && otherItem.Color == color;
}
public override int GetHashCode()
{
int hash = 19;
hash = hash * 31 + (text == null ? 0 : text.GetHashCode());
hash = hash * 31 + color.GetHashCode();
return hash;
}
}
现在IndexOf
应该可以正常工作。
(我已经实现了 IEquatable<ColorItem>
作为一般的良好实践,这是一个很好的措施。不过这里并不是绝对必要的。)
关于c# - List IndexOf 返回 -1 即使有匹配的对象 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16747480/