Heim  >  Artikel  >  Datenbank  >  ServiceStack.Redis 之 RedisClientList.Remove

ServiceStack.Redis 之 RedisClientList.Remove

WBOY
WBOYOriginal
2016-06-07 16:41:081480Durchsuche

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn