首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ASP.Net中,在system.web.caching中存储整数的最好方法是什么?

在ASP.Net中,在system.web.caching中存储整数的最好方法是什么?
EN

Stack Overflow用户
提问于 2012-01-27 09:45:22
回答 2查看 2.5K关注 0票数 3

目前,我必须将int转换为string并存储在缓存中,非常复杂

代码语言:javascript
复制
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

这里有没有一种更快的方法,不需要一次又一次地更改类型?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-27 09:51:11

您可以在缓存中存储任何类型的对象。方法签名为:

代码语言:javascript
复制
Cache.Insert(string, object)

因此,您不需要在插入前转换为字符串。但是,当您从缓存中检索时,需要强制转换:

代码语言:javascript
复制
int test = 123;
HttpContext.Current.Cache.Insert("key", test); 
object cacheVal = HttpContext.Current.Cache.Get("key");
if(cacheVal != null)
{
    test = (int)cacheVal;
}

这将导致原始类型的装箱/拆箱惩罚,但比每次通过字符串进行装箱/取消装箱的惩罚要小得多。

票数 6
EN

Stack Overflow用户

发布于 2012-01-27 09:56:45

您可以实现自己的方法来处理它,以便调用代码看起来更整洁。

代码语言:javascript
复制
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" );
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9028010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档