gpt4 book ai didi

asp.net - 为什么 Cache.Add 返回一个表示缓存项的对象?

转载 作者:行者123 更新时间:2023-12-02 09:04:30 25 4
gpt4 key购买 nike

From MSDN关于在 ASP.NET 缓存中添加或插入项目之间的差异:

Note: The Add and Insert methods have the same signature, but there are subtle differences between them. First, calling the Add method returns an object that represents the cached item, while calling Insert does not. Second, their behavior is different if you call these methods and add an item to the Cache that is already stored there. The Insert method replaces the item, while the Add method fails. [emphasis mine]

第二部分很简单。毫无疑问。

但是对于第一部分,为什么它要返回一个表示缓存项的对象?如果我尝试将一个项目添加到缓存中,我已经拥有/知道该项目是什么?

我不明白。这背后的原因是什么?

最佳答案

在缓存上调用 Add() 最终会调用具有以下签名的内部方法:

internal abstract CacheEntry UpdateCache(CacheKey cacheKey, 
CacheEntry newEntry, bool replace, CacheItemRemovedReason removedReason,
out object valueOld);

注意out object valueOld - 它被设置为当前位于缓存中“cacheKey”位置的对象,并作为 Add() 的结果返回。该文档具有误导性,它实际上不是返回的同一个对象 - 它是位于该相同键位置的任何对象。

这可以通过以下代码轻松验证:

 String x = "lorem";
String y = "ipsum";

HttpContext.Current.Cache.Add("hi", x, null, DateTime.MaxValue,
Cache.NoSlidingExpiration,
CacheItemPriority.Normal, null);

var z = HttpContext.Current.Cache.Add("hi", y, null, DateTime.MaxValue,
Cache.NoSlidingExpiration,
CacheItemPriority.Normal, null);

//Result:
// z == "lorem"

关于asp.net - 为什么 Cache.Add 返回一个表示缓存项的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1286359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com