词典TryGetValue NullReferenceException [英] Dictionary TryGetValue NullReferenceException
问题描述
我在 _dicCache.TryGetValue(objID,out newObject);
行中得到NullReferenceException。我没有理由为什么这是发生在所有。可以点我指向正确的方向吗?
I am getting NullReferenceException at the _dicCache.TryGetValue(objID, out newObject);
line. And I have no Idea why this is happening at all. Can comeone point me to the right direction please?
这是我的课程:
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类到:
I Also have tried to change to 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;
}
}
但是我仍然在$ $上获得相同的NullReferenceException c $ c> _dicCache.TryGetValue(objID,out newObject); line。
But I still get the same NullReferenceException at the _dicCache.TryGetValue(objID, out newObject);
line.
推荐答案
您可以使用该异常的唯一方法是您的字典为空。
I think the only way you could have that exception is if your dictionary is null.
_dicCache.TryGetValue(objID, out newObject);
null
是密钥的有效参数(如果 TKey
是一个引用类型),虽然在你的情况下它是 int
。
null
is a valid argument for the key (if TKey
is a reference type), though in your case it's int
.
您确定 _dicCache
不是 null
?我会检查作业的值:
Are you sure _dicCache
is not null
? I would check the value of the assignment:
_dicCache = (Dictionary<int, T>)HttpContext.Current.Cache.Get(Name);
这篇关于词典TryGetValue NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!