rpm*_*ins 4 .net c# dictionary nullreferenceexception
我在线上得到NullReferenceException _dicCache.TryGetValue(objID, out newObject);
.我不知道为什么会发生这种情况.可以告诉我正确的方向吗?
这是我的班级:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我称之为:
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);
Run Code Online (Sandbox Code Playgroud)
我也试图改为Get class to:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我仍然在线上得到相同的NullReferenceException _dicCache.TryGetValue(objID, out newObject);.
我认为,如果您的字典为空,那么您可以拥有该异常的唯一方法.
_dicCache.TryGetValue(objID, out newObject);
Run Code Online (Sandbox Code Playgroud)
null是键的有效参数(如果TKey是引用类型),但在您的情况下它是int.
你确定_dicCache不是null吗?我会检查作业的价值:
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);
Run Code Online (Sandbox Code Playgroud)