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

3

目前,我不得不把 int 转换成 string 并存储在缓存中,非常复杂。

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

有没有一种更快的方法,而不需要反复更改类型?
2个回答

6

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

Cache.Insert(string, object)

所以,您不需要在插入之前转换为字符串。然而,在从缓存中检索时,您需要进行类型转换:

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

这将导致基本类型的装箱/拆箱代价,但比每次通过字符串进行转换的代价要小得多。


test = (int)HttpContext.Current.Cache.Get("key"); 出现错误,无法将 string 类型转换为 int,必须使用 Parse,而要使用 Parse,必须先使用 .ToString() - Eric Yin
2
看起来您一开始没有存储整数。 typeof(HttpContext.Current.Cache.Get("key")).ToString() 是什么? - spender
你是正确的。但是我不认为我可以直接这样做,因为缓存可能为null,而(int)null会报错。 - Eric Yin

1

你可以实现自己的方法来处理它,这样调用代码看起来更简洁。

public void InsertIntIntoCache( string key, int value )
{
   HttpContext.Current.Cache.Insert( key, value );
}

public int GetIntCacheValue( string key )
{
   return (int)HttpContext.Current.Cache[key];
}

int test = 123;
InsertIntIntoCache( "key", test );
test = GetIntCacheValue( "key" );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接