在ASP.NET中,在System.Web.caching中存储int的最佳方式是什么?
题
目前,我必须将生成的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
.
这里是一种更快的方式而没有再次改变类型又一次?
解决方案
You can store any kind of object in the cache. The method signature is:
Cache.Insert(string, object)
so, you don't need to convert to string before inserting. You will, however, need to cast when you retrieve from the cache:
int test = 123;
HttpContext.Current.Cache.Insert("key", test);
object cacheVal = HttpContext.Current.Cache.Get("key");
if(cacheVal != null)
{
test = (int)cacheVal;
}
This will incur a boxing/unboxing penalty with primitive types, but considerably less so than going via string each time.
其他提示
You could implement your own method that handles it so the calling code looks cleaner.
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" );
不隶属于 StackOverflow