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方法,删除对象数据!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值