我在_dicCache.TryGetValue(objID, out newObject);生产线上找到了NullReferenceException。我完全不知道为什么会发生这种事。请来告诉我正确的方向好吗?
下面是我的类:
public class Cache<T>
{
public string Name { get; set; }
private Dictionary<int, T> _dicCache = new Dictionary<int, T>();
public void Insert(int objID, T obj)
{
try
{
_dicCache.Add(objID, obj);
HttpContext.Current.Cache.Insert(Name, _dicCache, null, DateTime.Now.AddMinutes(10), TimeSpan.FromMinutes(0));
}
catch (Exception)
{
throw;
}
}
public bool Get(int objID, out T obj)
{
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);
try
{
return _dicCache.TryGetValue(objID, out obj);
}
catch (Exception)
{
throw;
}
}
}我是这样称呼它的:
Services.Cache<Entities.User> cache = new Services.Cache<Entities.User>();
cache.Name = Enum.Cache.Names.usercache.ToString();
Entities.User user = new Entities.User();
cache.Get(pUserId, out user);我还尝试将类更改为:
public T Get(int objID, out T obj)
{
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);
T newObject = (T)Activator.CreateInstance<T>();
try
{
_dicCache.TryGetValue(objID, out newObject);
obj = newObject;
return obj;
}
catch (Exception)
{
throw;
}
}但我在_dicCache.TryGetValue(objID, out newObject);生产线上还是得到了同样的NullReferenceException。
发布于 2012-12-26 08:26:57
我认为唯一可能出现这种异常的方法是如果你的字典是空的。
_dicCache.TryGetValue(objID, out newObject);null是键的有效参数(如果TKey是引用类型),尽管在本例中它是int。
你确定_dicCache不是null吗?我会检查赋值的值:
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);发布于 2012-12-26 08:20:57
真正将_dicCache放入http上下文缓存中的方法是insert方法,它在您的代码中从未被调用过,因此当您试图从http上下文中获取它时,您会得到null (您只会调用Get)。
我会更改名称设置器,以便在那时将字典实际放入http上下文中,或者更好的做法是,通过获取Name属性作为构造函数参数,以某种方式将字典插入到构造函数的缓存中。一般来说,我试图以这样一种方式设计类,即它们在尽可能少的时间内处于“未初始化”状态。
https://stackoverflow.com/questions/14034873
复制相似问题