ServiceStack.Redis 之 RedisClientList.Remove

Q:使用 IRedisTypedClient.List[RepositoryKey].Remove(Item) 無效!

A:

public bool Remove(T item)
        {
            var index = this.IndexOf(item);
            if (index != -1)
            {
                this.RemoveAt(index);
                return true;
            }
            return false;
        }

可以看到

1.首先使用 IndexOf 獲得數據的下標索引。

2.通過 RemoveAt 刪除 索引位置的數據。

IndexOf 代碼如下:

        public int IndexOf(T item)
        {
            //TODO: replace with native implementation when exists
            var i = 0;
            foreach (var existingItem in this)
            {
                if (Equals(existingItem, item)) return i;
                i++;
            }
            return -1;
        }

其中Equals 作爲對象的比較,這裏請查看 Object.Equals 方法 。【它確定兩個對象是否表示同一對象引用。 如果成功,該方法返回 true.】

所以 Equals(existingItem, item) 恆等於 false => 返回值始終爲 -1=>RemoveAt(-1)=>始終會刪除失敗。

那麼我們如何解決呢?

這裏有2個方法:

1.我們重載比較對象的 Equals 方法

        public override bool Equals(Object obj)
        {
            if (obj == null || !(obj is EntityClass))
                return false;
            else
                return (this.Id== ((EntityClass)obj).Id);
        }

        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }

那麼對象之間的比較其實就是 對象 Id 值之間的比較。

  1. 跳過 Remove方法,直接使用RemoveAt方法。

獲得對象數據在List中的索引位置,直接調用RemoveAt方法,刪除對象數據!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章