List<T>.IndexOf
在列表中查找与您传递的值相等的项目。默认情况下,对于类,相等性只是对象身份 - 因此两个不同的对象被视为不相等,无论它们的字段是什么。但是,您可以通过覆盖该Equals
方法来更改它。
如果ColorItem
是您自己的课程,您绝对可以通过适当地覆盖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>
了很好的措施。不过,这里并不是绝对必要的。)