PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

ServiceStack.Redis 之 RedisClientList.Remove

原创
2016-06-07 16:41:08 1259浏览

Q:使用 IRedisTypedClientT.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 获得

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 值之间的比较。

2. 跳过 Remove方法,直接使用RemoveAt方法。

获得对象数据在List中的索引位置,直接调用RemoveAt方法,删除对象数据!

67b8673907a44df54d698&690

转载请注明:Ahoo » ServiceStack.Redis 之 RedisClientList.Remove

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。