首页 > 解决方案 > 静态只读初始化变量抛出空引用异常?

问题描述

堆栈跟踪

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

标签: c#staticnullreferenceexception

解决方案


推荐阅读