当C#中ArrayList存储对象为自定义对象时,使用IndexOf无法找自定义对象索引问题

当用 ArrayList 存储自己定义的类对象时,使用ArrayList的indexof(obj)无法找到正确的下标。

查看indexof的源代码显示为:

for (int j = startIndex; j < num; j++)
{
                object obj = array2[j];
                if (obj != null && obj.Equals(value))
                {
                    return j;
                }
}

 

 对象是引用类型,当使用两个对象比较时,由于引用地址不一致,所以判定;两个对象不相等。所以集合中自定义的对象需要重载 Equals方法,例如:

class CRation
    {
        public int n;//分子
        public int d;//分母
       

        // override object.Equals
        public override bool Equals(object obj)
        {
            

            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }
            CRation temp = (CRation)obj;
            if (this.n == temp.n && this.d == temp.d) return true;
            else return false;
          
        }

        // override object.GetHashCode
        public override int GetHashCode()
        {
            // TODO: write your implementation of GetHashCode() here
            // throw new NotImplementedException();
            return base.GetHashCode();
        }

    }

 

posted @ 2021-10-12 21:21  dabao2021  阅读(272)  评论(0编辑  收藏  举报