【发布时间】:2012-12-26 00:09:27
【问题描述】:
我在_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);
我也尝试将 Get 类更改为:
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。
【问题讨论】:
-
_dicCache可能为空。你确定(Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);这个演员表有效吗?调试这些行 -
你不需要初始化
newObject,因为它是由TryGetValue初始化的。问题绝对不在于它。 -
@Konstantin Vasilcov
_dicCache是null!我没有注意那个。非常感谢。 -
因为我像这样声明
_dicCache变量:private Dictionary<int, T> _dicCache = new Dictionary<int, T>();我认为它不会为空。你能解释为什么它是空的吗? -
那个
Name在缓存中有什么发现吗?
标签: c# .net dictionary nullreferenceexception