c# - 静态只读初始化变量抛出空引用异常?
问题描述
堆栈跟踪
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Mobile.DataStructures.Caching.Cache`2.Add(TKey key, TValue value, Func`1 autoRefresh, TimeSpan timeToExpire) in C:\Project\Caching\Cache.cs:line 68
at Mobile.DataStructures.Caching.Cache`2.Add(TKey key, TValue value, Func`1 autoRefresh) in C:\Project\Caching\Cache.cs:line 51
at Mobile.Authentication.Principal.PrincipalExtensions.AddUserPermissionsToCache(String username) in C:\Project\Helpers\Auth\PrincipalExtensions.cs:line 53
at Mobile.Authentication.Principal.PrincipalExtensions.RetrieveUserPermissions(PrincipalWithActivities principal, String username) in C:\Project\Helpers\Auth\PrincipalExtensions.cs:line 37
at Mobile.MvcApplication.Application_PostAuthenticateRequest(Object sender, EventArgs e) in C:\Project\Global.asax.cs:line 126
缓存.cs
public class Cache<TKey, TValue>
{
private static readonly IDictionary<TKey, CacheItem<TValue>> _Cache = new Dictionary<TKey, CacheItem<TValue>>();
...
/// <summary>
/// Adds the item to the cache where it will use the indicated autoRefresh function to refresh the value when expired.
/// Will set the time to expire to the indicated time.
/// </summary>
public void Add(TKey key, TValue value, Func<TValue> autoRefresh, TimeSpan timeToExpire)
{
var item = new CacheItem<TValue>()
{
Value = value,
RefreshCache = autoRefresh,
CachedOn = DateTime.Now,
TimeToExpire = timeToExpire
};
_Cache.Add(key, item); // NULL-REFERENCE EXCEPTION: This line threw the NullReferenceException.
TriggerChanged(new CacheEventArgs<TKey, TValue>(key, null, item));
// REFRESH: If the value is already null or default refresh it immediately.
if (item.Value == null || item.Value.Equals(default(TValue)))
{
var before = new CacheItem<TValue>(item);
item.Value = item.RefreshCache();
TriggerRefreshed(new CacheEventArgs<TKey, TValue>(key, before, item));
}
}
}
环境及其他细节
这是 ASP.NET MVC 5 项目的一部分,执行链的顶部是文件中的Application_PostAuthenticateRequest(object sender, EventArgs e)
事件global.asax
。
我只是在部署到服务器后才立即体验到这一点;但是,我觉得这应该能够发生。不应该在static
那时初始化变量吗?
问题
它是static
, readonly
,并且它有一个静态初始化器。这条线是如何_Cache.Add(key, item);
抛出的NullReferenceException
?
解决方案
推荐阅读
- rust - 如何为我的自定义结构(链表)实现复制特征以及如何在一个函数调用中循环链表
- java - 将带有前导特殊字符的字符串转换为双精度?
- haskell - 将 GADT 与 DataKinds 一起用于函数中的类型级数据构造函数约束
- connection - 德州仪器 DCA1000 雷达问题
- angular - 自定义 ErrorHandler 提供程序为响应异步事件而打开的对话框未关闭
- sql - Presto - 使用数组的每个索引将 2 个数组转换为单独的映射实体
- angular - AngularFire2 Microsoft Auth 提供 POST https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyAssertion 400
- c# - 查询一对一关系
- r - 对于在数据帧中创建新变量的循环,在 R 中运行多个数据帧
- mysql - 如何使用 docker-compose 将 csv 加载到 mysql 中?