3

我有以下代码来查找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。我错过了什么?

颜色列表内容

颜色项目内容

4

2 回答 2

6

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>了很好的措施。不过,这里并不是绝对必要的。)

于 2013-05-25T08:04:50.743 回答
1

您分配colorItemsp.TileColorItem,它不在colorList. 这就是为什么如果你调用colorList.IndexOf(colorItem)它返回-1。你可能想使用这样的东西:

int index;
foreach (var item in colorList)
{
    if (item.Text == sp.TileColorItem)
    {
        index = colorList.IndexOf(item);
    }
}
于 2013-05-25T07:39:40.833 回答