目前,我必须将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这里有没有一种更快的方法,不需要一次又一次地更改类型?
发布于 2012-01-27 09:51:11
您可以在缓存中存储任何类型的对象。方法签名为:
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-27 09:56:45
您可以实现自己的方法来处理它,以便调用代码看起来更整洁。
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" );https://stackoverflow.com/questions/9028010
复制相似问题