C# System.Web.Caching.Cache在模型中引发空异常
也许这个问题应该很简单,但事实并非如此。我读过 我有一个单身班:C# System.Web.Caching.Cache在模型中引发空异常,c#,asp.net-mvc-3,caching,data-caching,C#,Asp.net Mvc 3,Caching,Data Caching,也许这个问题应该很简单,但事实并非如此。我读过 我有一个单身班: private System.Web.Caching.Cache _cache; private static CacheModel _instance = null; private CacheModel() { _cache = new Cache(); } public static CacheModel Instance { get { return _instance
private System.Web.Caching.Cache _cache;
private static CacheModel _instance = null;
private CacheModel() {
_cache = new Cache();
}
public static CacheModel Instance {
get {
return _instance ?? new CacheModel();
}
}
public void SetCache(string key, object value){
_cache.Insert(key, value);
}
如果在我的代码中的任何其他地方,我调用以下命令:
CacheModel aCache = CacheModel.Instance;
aCache.SetCache("mykey", new string[2]{"Val1", "Val2"}); //this line throws null exception
为什么第二行抛出空引用异常
也许我在代码的某个地方犯了错误
谢谢。您不应该使用
缓存
类型:
此API支持.NET Framework基础架构,不打算直接从代码中使用
如果不直接研究为什么会出现空引用异常,我以前也遇到过这个问题,这是:
每个应用程序域都会创建此类的一个实例,只要该应用程序域保持活动状态,该类就会保持有效。有关此类实例的信息可通过HttpContext对象的Cache属性或Page对象的Cache属性获得
总之,不要以这种方式直接使用
System.Web.Caching.Cache
类型-要么访问现有的缓存实例,要么使用另一种方法,如上文所述的
改用System.Runtime.Caching。
下面是一个片段:
`
`
在ASP.NET 4中,缓存是通过使用ObjectCache类实现的。
using System.Runtime.Caching;
...
ObjectCache cache = MemoryCache.Default;
var test = "hello world";
cache["greeting"] = test;
var greeting = (string)cache["greeting"];