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

タイプを何度も変更せずに、より高速な方法はありますか?

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 に答える