3

目前,我必须转换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

这是一种更快的方法而无需一次又一次地更改类型吗?

4

2 回答 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;
}

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

于 2012-01-27T01:51:10.937 回答
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" );
于 2012-01-27T01:56:44.507 回答