在ASP.Net中,在system.web.caching中存储int的最佳方法是什么?

Eri*_*Yin 3 c# asp.net caching int32

目前,我必须转换intstring并存储在缓存中,非常复杂

int test = 123;
System.Web.HttpContext.Current.Cache.Insert("key", test.ToString()); // to save the cache
test = Int32.Parse(System.Web.HttpContext.Current.Cache.Get("key").ToString()); // to get the cache
Run Code Online (Sandbox Code Playgroud)

这是一个一次又一次没有改变类型的更快的方式吗?

spe*_*der 6

您可以在缓存中存储任何类型的对象.方法签名是:

Cache.Insert(string, object)
Run Code Online (Sandbox Code Playgroud)

所以,在插入之前不需要转换为字符串.但是,从缓存中检索时,您需要进行强制转换:

int test = 123;
HttpContext.Current.Cache.Insert("key", test); 
object cacheVal = HttpContext.Current.Cache.Get("key");
if(cacheVal != null)
{
    test = (int)cacheVal;
}
Run Code Online (Sandbox Code Playgroud)

这将导致原始类型的装箱/拆箱惩罚,但每次都比通过字符串少得多.

  • 看起来你没有首先存储一个int.什么是`typeof(HttpContext.Current.Cache.Get("key")).ToString()`? (2认同)