ASP.NET에서 System.Web.Caching에 int를 저장하는 가장 좋은 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/9028010

  •  14-11-2019
  •  | 
  •  

문제

현재, 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
.

여기서는 변경 유형이 없으면 더 빠른 방법으로 다시 표시됩니까?

도움이 되었습니까?

해결책

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" );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top