Dans ASP.Net, quelle est la meilleure façon de stocker un int dans le système.web.la mise en cache?
Question
Actuellement, je dois convertir int
pour string
et stocker dans le cache, très complexe
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
Est ici un moyen plus rapide sans changer le type, encore et encore?
La solution
Vous pouvez stocker n'importe quel type d'objet dans le cache.La signature de la méthode est:
Cache.Insert(string, object)
donc, vous n'avez pas besoin de convertir en string avant de l'insérer.Vous aurez cependant besoin de jeter lorsque vous récupérer à partir de la mémoire cache:
int test = 123;
HttpContext.Current.Cache.Insert("key", test);
object cacheVal = HttpContext.Current.Cache.Get("key");
if(cacheVal != null)
{
test = (int)cacheVal;
}
Cela entraînera une boxing/unboxing de pénalité avec les types primitifs, mais beaucoup moins que par l'intermédiaire de la chaîne à chaque fois.
Autres conseils
Vous pouvez implémenter votre propre méthode qui gère de sorte que le code appelant semble plus propre.
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" );
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow