时间:2021-07-01 10:21:17 帮助过:21人阅读
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
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方法,删除对象数据!

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